使用MSVC检测内存泄漏的方法如下:
- 开发环境使用 Visual Studio,或者只下载C++ build tool
方法1:在程序结束时调用 _CrtDumpMemoryLeaks()
#include <crtdbg.h>#ifdef _DEBUG#define new new (_NORMAL_BLOCK, __FILE__, __LINE__)#endifint main() {int* p = new int(42);_CrtDumpMemoryLeaks();}
上面代码有内存泄漏,在调试程序时会有如下提示:
方法2:在开始点使用 _CrtSetDbgFlag(),它在程序退出时自动调用 _CrtDumpMemoryLeaks()
#include <crtdbg.h>#include <memory>#ifdef _DEBUG#define new new (_NORMAL_BLOCK, __FILE__, __LINE__)#endifint main() {_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));auto p = std::make_shared<int>(42);}
上面程序没有内存泄漏。
