In the following code, s
is allocated using calloc and is never freed. But cppcheck does not detect that memory leak if it is passed to f1
. Based on the cppcheck documentation, I believe it assumes that f1
may be taking care of it.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef CALL_F1
void f1(const char *s)
{
printf("%sn", s);
}
#endif
int main()
{
char *s = calloc(10, sizeof(char));
printf("%sn", s); // use s to avoid unused warning
#ifdef CALL_F1
f1(s);
#endif
return 0;
}
Here is how I am invoking cppcheck (v2.7)
$ cppcheck -UCALL_F1 test.c
Checking test.c ...
test.c:19:2: error: Memory leak: s [memleak]
return 0;
^
$ cppcheck -DCALL_F1 test.c
Checking test.c ...
Checking test.c: CALL_F1=1...
I know we can use <leak-ignore />
on a function to explicitly tell cppcheck that it is not freed in that function, but the docs say “if cppcheck doesn’t know what dostuff does”. But in this case, cppcheck clearly knows what it does, the code is available. And it is not practical to add leak-ignore flags for every function that accepts a pointer.
So my question is, is there a way to override this behaviour? I feel that as long as a pointer is passed around in the same file, and it doesn’t call any library functions that doesn’t have <noreturn>
associated with it, I don’t see why the tool cannot ignore it.
I found a similar question, but that hasn’t been answered properly; the sole answer just says it works for them, but it doesn’t work with the latest version of cppcheck.