Monday, May 4, 2009

Easy way to check memory leak

Instead of overload new operator by ourself, we can use visual studio debugger and  c runtime library to detect memory leak.

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

#if defined(_DEBUG) && !defined(DEBUG_NEW)
#define _CRTDBG_MAP_ALLOC
#include < stdlib.h > 
#include < crtdbg.h >
#define DEBUG_NEW new(_NORMAL_BLOCK,THIS_FILE,__LINE__)
#endif

crtdbg.h gives debug version  of malloc and free function and these functions can track memory leak in debug mode. 
Next add _CrtDumpMemoryLeaks() in the place where you want to check memory leak.
If memory leak happens you will get info like this:
d:\l\projects\myprogram\dxengine\dxengine\dxengine\stdafx.h(121) : {216} normal block at 0x009C7B10, 20 bytes long.
 Data: <        <       > 00 05 00 00 20 03 00 00 3C 00 00 00 16 00 00 00
Next according to the memory leak block number 216,add this line at the beginning of the program to tell application to break on the memory leak point.
_CrtSetBreakAlloc(216);

Read More...