標籤:art blog details normal pre c++ ble file article
定位記憶體流失是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
vs 2017/2015/2013 如何定位C++記憶體流失