xref: /llvm-project/clang/docs/analyzer/checkers/unix_malloc_example.c (revision 1a17032b788016299ea4e3c4b53670c6dcd94b4f)
1*1a17032bSKristof Umann 
test()2*1a17032bSKristof Umann void test() {
3*1a17032bSKristof Umann   int *p = malloc(1);
4*1a17032bSKristof Umann   free(p);
5*1a17032bSKristof Umann   free(p); // warn: attempt to free released memory
6*1a17032bSKristof Umann }
7*1a17032bSKristof Umann 
test()8*1a17032bSKristof Umann void test() {
9*1a17032bSKristof Umann   int *p = malloc(sizeof(int));
10*1a17032bSKristof Umann   free(p);
11*1a17032bSKristof Umann   *p = 1; // warn: use after free
12*1a17032bSKristof Umann }
13*1a17032bSKristof Umann 
test()14*1a17032bSKristof Umann void test() {
15*1a17032bSKristof Umann   int *p = malloc(1);
16*1a17032bSKristof Umann   if (p)
17*1a17032bSKristof Umann     return; // warn: memory is never released
18*1a17032bSKristof Umann }
19*1a17032bSKristof Umann 
test()20*1a17032bSKristof Umann void test() {
21*1a17032bSKristof Umann   int a[] = { 1 };
22*1a17032bSKristof Umann   free(a); // warn: argument is not allocated by malloc
23*1a17032bSKristof Umann }
24*1a17032bSKristof Umann 
test()25*1a17032bSKristof Umann void test() {
26*1a17032bSKristof Umann   int *p = malloc(sizeof(char));
27*1a17032bSKristof Umann   p = p - 1;
28*1a17032bSKristof Umann   free(p); // warn: argument to free() is offset by -4 bytes
29*1a17032bSKristof Umann }
30*1a17032bSKristof Umann 
31