Memory Leak detection with Microsoft Visual C++ – Part 1

September 6th, 2009 Leave a Comment

As a programmer/software engineer, memory leak has always been our enemy. It has been mine for sure, if not for you.

Well, I’m going to share with you a library that comes with MS Visual C++ to detect memory leak in your program, if you’ve not already known. This works only in debug version though. If you want to check memory leak in a release version, you may need to write your own memory manager (I hope that I’d have more time to cover that next time).

I’ll include some code snippets here for you to try it out. But of course, you’ve gotta have some prior knowledge with C++ :)

First, you need to insert the followings at the top of your code, preferably in the same file as main function.

#include <stdlib.h>
#include <crtdbg.h>

To enable memory leak dump when your program exits, you’ve got to include the following code, preferably after main function.

int iDbgFlag;
iDbgFlag  = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

You can see the leak report in the Visual Studio’s output window when you run (in debug mode) directly from the VC++. It will indicate the file name and line number of the allocation that hasn’t been freed. It looks somewhat like the followings, depending on your amount of leaks.

test.cpp(11) : {64} normal block at 0x00355D88, 64 bytes long.
Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.

So, I hope this does help you in battling the memory leaks in your program, if any. Lastly, I wish you happy programming ;)

, , ,

Leave a Reply

five + = 6