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


Question

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.

1
123
8/22/2017 5:17:32 PM

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

78
4/16/2012 12:57:45 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon