How to Detect Memory Leaks within Visual C++

This is a useful technique while developing any application that has a lot of memory allocations. It isn't really that good if you've got a completed project and you want to check memory leaks over a ton of code. And I wouldn't say that this is very good if you are used to using Purify or some similar tool. But this is free and a neat compiler trick.

First of all, this only works in Debug builds. The trick is to turn on a few flags using VC++ specific macros defined in crtdbg.h:


#include  "crtdbg.h"

.
.
.
// put these close to WinMain (or main) entrance
#ifndef NDEBUG

// get current dbg flag (report it)
int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

// logically OR leak check bit
flag |= _CRTDBG_LEAK_CHECK_DF;

// set the flags again
_CrtSetDbgFlag(flag); 

#endif


If you add this and run your program within the IDE, you'll get some statements in the Output window when you exit your program:


Detected memory leaks!
Dumping objects ->
{42} normal block at 0x002F51F0, 1000 bytes long
Data: /
     <            > CD CD CD CD CD ...
Object dump complete

That tells you there are memory leaks and how big they are but the address and data dump are of little use to us. We can take this code to find memory leaks and extend it further by going to the source: the new operator. Because new is an operator, we can overload it with our new and improved memory leak reporter. This overloaded version will report the file and the line the memory allocation took place on when we have a leak. Then during debugging, we can identify which pointers weren't deleted and fix them:


// put this right after the flag settings from above
#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)

#endif

Now the output window will show the path and line number (in parenthesis next to path) of where the new operator was called that lead to a leak. This is much more helpful!
A few more notes: