Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / clang / test / Analysis / malloc-static-storage.cpp
blob4eeabab41209b8738ceca913cf72ef6b27e54ffb
1 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc -verify %s
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);
8 void escape(void *);
9 void next_statement();
11 void conditional_malloc(bool coin) {
12 static int *p;
14 if (coin) {
15 p = (int *)malloc(sizeof(int));
17 p = 0; // Pointee of 'p' dies, which is recognized at the next statement.
18 next_statement(); // expected-warning {{Potential memory leak}}
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}}
31 void malloc_escape() {
32 static int *p;
33 p = (int *)malloc(sizeof(int));
34 escape(p); // no-leak
35 p = 0; // no-leak
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}}
48 int *malloc_return_static() {
49 static int *p = (int *)malloc(sizeof(int));
50 return p; // no-leak
53 int malloc_unreachable(int rng) {
54 // 'p' does not escape and never freed :(
55 static int *p;
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;
62 if (rng > 0)
63 *p = rng;
65 return *p; // FIXME: We just leaked 'p'. We should warn about this.
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}}
76 escape(&p);