精選文章

SmallBurger Asset Home

  SmallBurger

2012年2月4日 星期六

快速自製windows下MemoryLeak檢查函式…

相信很多人都已經知道VC的crtdbg不錯用(MFC也是用這個檢查Memory Leak),在此提供給不知道的人參考,相關打包函式如下(記得放在.h,覆寫掉New操作元):
//WindowsMemoryLeakCheck.h
#include < crtdbg.h >
#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
inline void EnableMemLeakCheck(unsigned int uiBreakID = 0)
{
  _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) |
    _CRTDBG_LEAK_CHECK_DF);
  if(uiBreakID != 0)
    _CrtSetBreakAlloc(uiBreakID);
}


然後在程式執行起始的地方呼叫EnableMemLeakCheck這個函式,比方:
#include "WindowsMemoryLeakCheck.h"
int main(int argc, char* argv[])
{
  EnableMemLeakCheck();
  char* pTemp = new char[128];
  …
}

執行程式後離開可能會產生以下資訊…
Detected memory leaks!
Dumping objects ->
{1246} normal block at 0x02658970, 128 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
The program '[5260] MultipleViewportsTestAPP.exe: Native' has exited with code 0 (0x0).

紅色數字為程式產生leak位置的ID,將此ID當參數代入後,即可由CallStack裡找到真正Leak的位置,比方:
EnableMemLeakCheck(1246);


然後會當在這個地方:
 /* break into debugger at specific memory allocation */
if (_crtBreakAlloc != -1L && lRequest == _crtBreakAlloc)
   _CrtDbgBreak();
查CallStack後,發現位置如下:
char* pTemp = new char[128];
就介紹到這裡,希望可以幫助到需要的人…

沒有留言:

張貼留言