Steps To Detect Memory Leak(Draft)

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.


 

 

 

posted @ 2008-08-13 23:21  能巴  阅读(406)  评论(0编辑  收藏  举报