Example 54 Potential memory leak check
Cadvise detects potential memory leaks in the program where the memory allocated in the program is not freed. If a dynamically allocated memory becomes unreachable from any other pointers, then the memory is leaked after that point in the program, assuming that there is no garbage collection in the allocator. Cadvise flags such situations as shown in the following example code fragment:
#include <stdlib.h> #include <stdio.h> #include <string.h>
int leak1 (int k, int some_condition)
{
char *p = malloc (k); if (p == 0) return
if (some_condition) return
printf ("%s\n", p); free (p);
return 0;
}
int* leak2(int k, char* fname)
{
FILE* f;
int *p = (int*) malloc(k); if (p == 0) return 0;
//after return, memory pointed to by 'p' is leaked if ((f = fopen(fname,"r")) == 0) return 0; fread(p, k,1, f);
return p;
}
In such cases, cadvise generates the following warnings:
"memleak.c", line 13, procedure leak1: warning
"memleak.c", line 27, procedure leak2: warning
However, there can be false positives flagged in certain situations because of the conservative static analysis.