Clang Project

clang_source_code/test/Analysis/free.c
1// RUN: %clang_analyze_cc1 -fblocks -verify %s -analyzer-store=region \
2// RUN:   -analyzer-checker=core \
3// RUN:   -analyzer-checker=unix.Malloc
4//
5// RUN: %clang_analyze_cc1 -fblocks -verify %s -analyzer-store=region \
6// RUN:   -analyzer-checker=core \
7// RUN:   -analyzer-checker=unix.Malloc \
8// RUN:   -analyzer-config unix.DynamicMemoryModeling:Optimistic=true
9typedef __typeof(sizeof(int)) size_t;
10void free(void *);
11void *alloca(size_t);
12
13void t1 () {
14  int a[] = { 1 };
15  free(a); // expected-warning {{Argument to free() is the address of the local variable 'a', which is not memory allocated by malloc()}}
16}
17
18void t2 () {
19  int a = 1;
20  free(&a); // expected-warning {{Argument to free() is the address of the local variable 'a', which is not memory allocated by malloc()}}
21}
22
23void t3 () {
24  static int a[] = { 1 };
25  free(a); // expected-warning {{Argument to free() is the address of the static variable 'a', which is not memory allocated by malloc()}}
26}
27
28void t4 (char *x) {
29  free(x); // no-warning
30}
31
32void t5 () {
33  extern char *ptr();
34  free(ptr()); // no-warning
35}
36
37void t6 () {
38  free((void*)1000); // expected-warning {{Argument to free() is a constant address (1000), which is not memory allocated by malloc()}}
39}
40
41void t7 (char **x) {
42  free(*x); // no-warning
43}
44
45void t8 (char **x) {
46  // ugh
47  free((*x)+8); // no-warning
48}
49
50void t9 () {
51label:
52  free(&&label); // expected-warning {{Argument to free() is the address of the label 'label', which is not memory allocated by malloc()}}
53}
54
55void t10 () {
56  free((void*)&t10); // expected-warning {{Argument to free() is the address of the function 't10', which is not memory allocated by malloc()}}
57}
58
59void t11 () {
60  char *p = (char*)alloca(2);
61  free(p); // expected-warning {{Memory allocated by alloca() should not be deallocated}}
62}
63
64void t12 () {
65  char *p = (char*)__builtin_alloca(2);
66  free(p); // expected-warning {{Memory allocated by alloca() should not be deallocated}}
67}
68
69void t13 () {
70  free(^{return;}); // expected-warning {{Argument to free() is a block, which is not memory allocated by malloc()}}
71}
72
73void t14 (char a) {
74  free(&a); // expected-warning {{Argument to free() is the address of the parameter 'a', which is not memory allocated by malloc()}}
75}
76
77static int someGlobal[2];
78void t15 () {
79  free(someGlobal); // expected-warning {{Argument to free() is the address of the global variable 'someGlobal', which is not memory allocated by malloc()}}
80}
81
82void t16 (char **x, int offset) {
83  // Unknown value
84  free(x[offset]); // no-warning
85}
86