Table of Contents
Looking for memory leaks and resource leaks is a key feature of Cppcheck. Cppcheck can detect many common mistakes by default. But through some tweaking you can improve the checking.
Cppcheck
understands many common allocation and
deallocation functions. But not all.
Here is example code that might leak memory or resources:
void foo(int x) { void *f = CreateFred(); if (x == 1) return; DestroyFred(f); }
If you analyse that with Cppcheck it won't find any leaks:
cppcheck --enable=possibleError fred1.cpp
You can add some custom leaks checking by providing simple implementations for the allocation and deallocation functions. Write this in a separate file:
void *CreateFred() { return malloc(100); } void DestroyFred(void *p) { free(p); }
When Cppcheck see this it understands that CreateFred will return allocated memory and that DestroyFred will deallocate memory.
Now, execute Cppcheck
this way:
cppcheck --append=fred.cpp fred1.cpp
The output from cppcheck is:
Checking fred1.cpp... [fred1.cpp:5]: (error) Memory leak: f