Thursday, March 25, 2010

Detecting Memory leak in Visual Studio (Debug mode)

Microsoft Visual Studio (2003/2005) informs about memory leakes in a module by setting the "leak check" bit, _CRTDBG_LEAK_CHECK_DF, to the debugger.

The memory leak information is printed on "Output" window.
[ This advantage is in "Debug" mode only. ]

For example,

int _tmain()
{
int* ptr = NULL;

ptr = (int*)malloc(sizeof(int)*20);

for( int i=0; i<20; ++i )
ptr[i] = i;

#ifndef NDEBUG

int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Get current flag

flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit

_CrtSetDbgFlag(flag); // Set flag to the new value

#endif

//free(ptr);

printf("\n\nPress Enter...");
getch();
return 0;
}

If we run the above program, we can see the memory leak information in an "Output" window as follows...

Detected memory leaks!
Dumping objects ->
{56} normal block at 0x02D42D48, 80 bytes long.
Data: < > 00 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00
Object dump complete.

Of course, the above information is not describes where the mem leak is present and in which file etc.., but the information is valid.

No comments: