定位內存泄漏是C++的一個大問題
我們可以通過如下方式進行定位:
//在主函數文件中加入如下代碼 #include <stdlib.h> #include <crtdbg.h> #ifdef _DEBUG #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) #endif void EnableMemLeakCheck() { int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmpFlag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmpFlag); } using namespace std; int main() { EnableMemLeakCheck(); //_CrtSetBreakAlloc(這里有第一遍注釋掉, 第二遍再執行); 自己的代碼 }
在 debug 模式下,可以看到如下信息:
此時我們注意大括號的內容,這就是可以我們的程序內存泄漏的地方。
將上面注釋掉的代碼加入,並將大括號的數字填入,就可以讓程序停在內存泄漏的地方。
如下,這里我們讓程序停在 556 處
//在主函數文件中加入如下代碼 #include <stdlib.h> #include <crtdbg.h> #ifdef _DEBUG #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) #endif void EnableMemLeakCheck() { int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); tmpFlag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(tmpFlag); } using namespace std; int main() { EnableMemLeakCheck(); //_CrtSetBreakAlloc(556); 自己的代碼 }
參考:http://blog.csdn.net/dyx810601/article/details/52092835