78 lines · cpp
1// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc -verify %s2 3typedef __typeof(sizeof(int)) size_t;4void* malloc(size_t size);5void *calloc(size_t num, size_t size);6void free(void * ptr);7 8void escape(void *);9void next_statement();10 11void 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 21void 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 31void malloc_escape() {32 static int *p;33 p = (int *)malloc(sizeof(int));34 escape(p); // no-leak35 p = 0; // no-leak36}37 38void free_whatever_escaped();39void 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 48int *malloc_return_static() {49 static int *p = (int *)malloc(sizeof(int));50 return p; // no-leak51}52 53int 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 68void 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}78