#include <string.h> #define _CRTDBG_MAP_ALLOC
#include <crtdbg.h> int _tmain(int argc, _TCHAR* argv[])
{
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); // 存储内存变量
_CrtMemState ms1, ms2, ms3; // 设置内存快照ms1
_CrtMemCheckpoint(&ms1); int* pInt = new int();
char* pStr = new char[]; strcpy(pStr, "TestApp");
delete pInt; // 设置内存快照ms2
_CrtMemCheckpoint(&ms2); // 比较两个快照, 这里没有释放pStr,应该被捕获到内存泄露
if (_CrtMemDifference(&ms3, &ms1, &ms2))
{
printf("\n Memory leak detected \n");
// 输出内存泄露上下文, 默认为vs output窗口。这里输出到控台应用程序窗口中(前面两行代码的重定向)
_CrtDumpMemoryLeaks();
}
else
{
printf("No memory leak \n");
} return ;
}