现在的位置: 首页 > 综合 > 正文

Steps To Detect Memory Leak(Draft)

2012年06月11日 ⁄ 综合 ⁄ 共 988字 ⁄ 字号 评论关闭

1. Use _CrtDumpMemoryLeaks() to check whether there is memory leak in program.

 

With the help of  _CRTDBG_MAP_ALLOC, it can output memory leak info with file line info for those memory block allocated by malloc(), while it would never print file line info for those allocated by new().

 

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

 

Call 

{

      _CrtDumpMemoryLeaks();

}

at the end of the program exit if there is only one exit in the program.

 

OR

Call

{

     _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

}

at the beginning of your program to ensure _CrtDumpMemoryLeaks() would be called when the program exits from any exit point.

 

2. Use DEBUG_NEW method to check in detail

 

#define DEBUG_NEW new(_NORMAL_BLOCK, THIS_FILE, __LINE__)

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

#endif

 

{

     _CrtMemDumpAllObjectsSince(NULL);

}

 

3. Use Tool like LeakFinder (Here: http://www.codeproject.com/KB/applications/leakfinder.aspx)

I still prefer to use shared_ptr to manage heap allocation instead of putting too much effort on detecting memory leak.

 

Keep on learning.

 

 

 

抱歉!评论已关闭.