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.


How To Hard Code a Break Point

September 23, 2008

I’m sure you are familiar with debug break points (press F9 in Visual Studio and a break point is there for you). What about programatically putting a break point? Try the following.

__asm int 3;


How To Show Compilation Duration in Visual Studio

September 22, 2008

Just add /Y3 in the shortcut command line of VC++ 6.

“C:\Program Files\Microsoft Visual Studio\Common\MSDev98\Bin\MSDEV.EXE” /y3

The compiler will show how much time it took to compile the whole project.

In Visual Studio .NET, you can set this option under Options –> Projects –> Build.