How To Find Memory Leaks With The Debugger

September 24, 2008

Visual studio debugger is a wonderful invention. See how it can show memory leaks (memory not properly de allocated) on exiting a program.


#include "afx.h"

// To show the memory leaks on exit
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

int main()
{ 
   char* str = new char[10];  // This won't be deallocated
   return 0;
}

See the following screen shot.

If DEBUG_NEW (defined in afx.h) is used, memory will be allocated in on a memory tracking basis (in the debug version).

You have to declare the above block in each file you need memory tracking.

Some Background Info

VC++ debugger defines some magic values for each type of memory location allocated.

0XCDCDCDCD – Memory allocated in heap, but not initialized

0xDDDDDDDD – Heap memory released

0xFDFDFDFD – Specifies the boundary of heap memory. It should not be overwritten as it designated the end.

0XCCCCCCCC – Memory allocated in stack, but not initialized.