Why does cppcheck
fail to detect a memory leak in a program like this example, where ownership of a heap pointer is passed to a function that fails to free it?
#include <stdlib.h>
void func(char *xx)
{
// do nothing
}
int main(void)
{
char *p = malloc(1000);
func(p);
return 0;
}
If I remove the call to func(p)
then cppcheck does detect the leak.
I am using Cppcheck 1.69 and this correctly informed me there was a memory leak. I have the following code:
#include <stdlib.h>
void func(char *xx)
{
// do nothing
}
int main(void)
{
char *p = (char*)malloc(1000);
func(p);
return 0;
}
Note that I have converted malloc
to a char*
to compile, but I tried Cppcheck with the exact same code you posted and it still correctly told me there was a memory leak.
When I run:
cppcheck main.cpp
I'm presented the following:
C:\Program Files (x86)\Cppcheck>cppcheck main.cpp
Checking main.cpp...
[main.cpp:12]: (error) Memory leak: p
I checked the change log for 1.69 and interestingly it says:
Improvements:
- Improved buffer overrun and memory leak checking
Cppcheck also correctly informs me of a memory leak if I use new
:
char* p = new char;
func(p);
And if I deallocate the memory in func
there is no error:
void func(char *xx)
{
delete p;
}
int main(void)
{
char* p = new char;
func(p);
return 0;
}
If I allocate with malloc
and try to deallocate with delete
in func
, Cppcheck also informs me of a mismatchAllocDealloc
error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.