原博客地址:https://blog.csdn.net/sinat_20265495/article/details/51763084
方法一:
#ifdef _DEBUG
#define New new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#define CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
//在入口函數中包含 _CrtDumpMemoryLeaks();
//即可檢測到內存泄露
//以如下測試函數爲例:
int main()
{
char* pChars = New char[10];
_CrtDumpMemoryLeaks();
return 0;
}
方法二:
#define CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
//在入口函數中包含 _CrtDumpMemoryLeaks();
//即可檢測到內存泄露
//定義函數:
inline void EnableMemLeakCheck()
{
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
}
//該函數可以放在主函數的任意位置,都能正確的觸發內存泄露輸出
//以如下測試函數爲例:
int main()
{
EnableMemLeakCheck();
char* pChars = new char[10];
//_CrtDumpMemoryLeaks();
return 0;
}