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.
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
...
void DetectLeaks()
{
    // Create some leaks.
    CString* pString = new CString;
    BYTE* pBuffer = new BYTE[100];

    // Dump memory leaks to output window.
    _CrtDumpMemoryLeaks();
}

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__;
#endif

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

Advertisements