| 1 |
// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc -verify %s |
| 2 |
|
| 3 |
typedef __typeof(sizeof(int)) size_t; |
| 4 |
void* malloc(size_t size); |
| 5 |
void *calloc(size_t num, size_t size); |
| 6 |
void free(void * ptr); |
| 7 |
|
| 8 |
void escape(void *); |
| 9 |
void next_statement(); |
| 10 |
|
| 11 |
void conditional_malloc(bool coin) { |
| 12 |
static int *p; |
| 13 |
|
| 14 |
if (coin) { |
| 15 |
p = (int *)malloc(sizeof(int)); |
| 16 |
} |
| 17 |
p = 0; // Pointee of 'p' dies, which is recognized at the next statement. |
| 18 |
next_statement(); // expected-warning {{Potential memory leak}} |
| 19 |
} |
| 20 |
|
| 21 |
void malloc_twice() { |
| 22 |
static int *p; |
| 23 |
p = (int *)malloc(sizeof(int)); |
| 24 |
next_statement(); |
| 25 |
p = (int *)malloc(sizeof(int)); |
| 26 |
next_statement(); // expected-warning {{Potential memory leak}} |
| 27 |
p = 0; |
| 28 |
next_statement(); // expected-warning {{Potential memory leak}} |
| 29 |
} |
| 30 |
|
| 31 |
void malloc_escape() { |
| 32 |
static int *p; |
| 33 |
p = (int *)malloc(sizeof(int)); |
| 34 |
escape(p); // no-leak |
| 35 |
p = 0; // no-leak |
| 36 |
} |
| 37 |
|
| 38 |
void free_whatever_escaped(); |
| 39 |
void malloc_escape_reversed() { |
| 40 |
static int *p; |
| 41 |
escape(&p); |
| 42 |
p = (int *)malloc(sizeof(int)); |
| 43 |
free_whatever_escaped(); |
| 44 |
p = 0; // FIXME: We should not report a leak here. |
| 45 |
next_statement(); // expected-warning {{Potential memory leak}} |
| 46 |
} |
| 47 |
|
| 48 |
int *malloc_return_static() { |
| 49 |
static int *p = (int *)malloc(sizeof(int)); |
| 50 |
return p; // no-leak |
| 51 |
} |
| 52 |
|
| 53 |
int malloc_unreachable(int rng) { |
| 54 |
// 'p' does not escape and never freed :( |
| 55 |
static int *p; |
| 56 |
|
| 57 |
// For the second invocation of this function, we leak the previous pointer. |
| 58 |
// FIXME: We should catch this at some point. |
| 59 |
p = (int *)malloc(sizeof(int)); |
| 60 |
*p = 0; |
| 61 |
|
| 62 |
if (rng > 0) |
| 63 |
*p = rng; |
| 64 |
|
| 65 |
return *p; // FIXME: We just leaked 'p'. We should warn about this. |
| 66 |
} |
| 67 |
|
| 68 |
void malloc_cond(bool cond) { |
| 69 |
static int *p; |
| 70 |
if (cond) { |
| 71 |
p = (int*)malloc(sizeof(int)); |
| 72 |
free_whatever_escaped(); |
| 73 |
p = 0; // FIXME: We should not report a leak here. |
| 74 |
next_statement(); // expected-warning {{Potential memory leak}} |
| 75 |
} |
| 76 |
escape(&p); |
| 77 |
} |