In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;)
We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero.
I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.)
I am expecting your experiences, suggestions and maybe some references to tools which simplify this.
Never used it myself, but my C friends tell me Purify.
Microsoft VC++ in debug mode shows memory leaks, although it doesn't show where your leaks are.
If you are using C++ you can always avoid using new explicitly: you have
vector
,string
,auto_ptr
(pre C++11; replaced byunique_ptr
in C++11),unique_ptr
(C++11) andshared_ptr
(C++11) in your arsenal.When new is unavoidable, try to hide it in a constructor (and hide delete in a destructor); the same works for 3rd party APIs.
I’m amazed no one mentioned DebugDiag for Windows OS.
It works on release builds, and even at the customer site.
(You just need to keep your release version PDBs, and configure DebugDiag to use Microsoft public symbol server)
Visual Leak Detector is a very good tool, altough it does not supports the calls on VC9 runtimes (MSVCR90D.DLL for example).
The best defense against leaks is a program structure which minimizes the use of malloc. This is not only good from a programming perspective, but also improves performance and maintainability. I'm not talking about using other things in place of malloc, but in terms of re-using objects and keeping very explicit tabs on all objects being passed around rather than allocating willy-nilly like one often gets used to in languages with garbage collectors like Java.
For example, a program I work on has a bunch of frame objects representing image data. Each frame object has sub-data, which the frame's destructor frees. The program keeps a list of all frames that are allocated, and when it needs a new one, checks a list of unused frame objects to see if it can re-use an existing one rather than allocate a new one. On shutdown, it just iterates through the list, freeing everything.
Mtrace appears to be the standard built-in one for linux. The steps are :
MALLOC_TRACE=/tmp/mtrace.dat
export MALLOC_TRACE;
mtrace your_prog_exe_name /tmp/mtrace.dat
(I had to install the mtrace perl script first on my fedora system with yum install glibc_utils )