How do you detect/avoid Memory leaks in your (Unmanaged) code?

prakash picture prakash · Sep 5, 2008 · Viewed 160.8k times · Source

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.

Answer

Jordi Bunster picture Jordi Bunster · Sep 5, 2008

If your C/C++ code is portable to *nix, few things are better than Valgrind.