//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];
就介紹到這裡,希望可以幫助到需要的人…
沒有留言:
張貼留言