How to hunt memory leaks using Visual Studio

Make sure you compile debug version of your project.

Press F5 (Start Debugging)

Do whatever you suspect to leak memory, and close program.

In output window you should see:

Detected memory leaks!
Dumping objects ->
{8677} normal block at 0x01AA4E08, 68 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

Add:

#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#define _INC_MALLOC
#endif

in your stdafx.h file, and recompile whole solution.

Now it should be something like:

Detected memory leaks!
Dumping objects ->
C:\Program Files\Microsoft Visual Studio 8\VC\include\crtdbg.h(1147) : {8677} normal block at 0x01AA4E08, 68 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

The problem is it shows allocator code, not your allocation itself. Still not very usefull. Now tricky part. Double click

C:\Program Files\Microsoft Visual Studio 8\VC\include\crtdbg.h line.

Set a trap (F9/Debug->Toggle Breakpoint) right click on the red dot and select condition and type _Size==<your leak size in this case 68>. Next time you will debug, program will stop if there will be 68 bytes allocated, then you can select Debug->Windows->Call Stack and if you are lucky you will see your memory leak.

Hunt memory leaks using Visual Studio & Deleaker

Another way to hunt memory leaks is using a useful tools called Deleaker.

Deleaker is a plugin for Visual Studio, when you enable it, you have access to the deleaker windows.

When you perform a execution of your program in debug, deleaker start to analyse your code and provide you all information about memory leaks.

I have made a basic test with a array of object without deleting all created object. Deleaker have detected all unreleased objects ( 10 Hits ).

The screenshot above show when i release correctly all objects. Deleaker do the job 🙂

Above, the deleaker configuration options…