【C++】Visual定位內存泄漏方法

原博客地址: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;  
} 

發佈了54 篇原創文章 · 獲贊 11 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章