How to detect Memory Leaks by using CRT?

17 06 2008

Memory leaks are every programmers nightmare. Usually we used to use memory leak detection tools such as Numega BoundsChecker, Rational Purify to find memory leaks. But do you know that our C Runtime library have pretty good support for isolating memory leaks?

You’ve to enable memory leak tracking by defining constant – _CRTDBG_MAP_ALLOC and then call – _CrtDumpMemoryLeaks(). Now the leaks will be dumped to the Visual Studio output window. See the following code snippet.

// Declare this in header.
#include <crtdbg.h>
void DetectLeaks()
    // Create some leaks.
    CString* pString = new CString;
    BYTE* pBuffer = new BYTE[100];

    // Dump memory leaks to output window.

When you call _CrtDumpMemoryLeaks() the memory leak information will be dumped to the output window. For instance, see the dump for memory leaks that we’ve made in DetectLeaks().

Detected memory leaks!
Dumping objects ->
C:\Jijo\Studies\VC++\MFC\RabbitDlg\RabbitDlgDlg.cpp(183) : {194} normal block at 0x00294990, 100 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
C:\Jijo\Studies\VC++\MFC\RabbitDlg\RabbitDlgDlg.cpp(182) : {193} normal block at 0x00293B20, 4 bytes long.
 Data: <   _> 14 FB 8C 5F
Object dump complete.

The filename and line number of leak will be present in the dump. So easy, nah?

While creating your MFC applications, did you ever noticed a code block as follows in your files?

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;

This is for debug information. By using this information, the _CrtDumpMemoryLeaks() keep track of the filename. If you comment out this, the filename will not be present in the dump which will make our task difficult. So never remove those line. I swear, they are really important! 😉

Targeted Audience – Intermediate



One response

9 09 2009


I am very new to this Memory leak detection. so i needed some help from you. I have an MDI application in which i need to detect the Memory leaks.
So my query here is do we need to speciy this
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
in all the files?

And also wat i found in CRT Memory leak detector is that for some memory leak it would specify the filename but for others it would not, how can we overcome this?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: