1 #include <string.h>
2
3 #define _CRTDBG_MAP_ALLOC
4 #include
5
6 int _tmain(int argc, _TCHAR* argv[])
7 {
8 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
9 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
10
11 // 存储内存变量
12 _CrtMemState ms1, ms2, ms3;
13
14 // 设置内存快照ms1
15 _CrtMemCheckpoint(&ms1);
16
17 int* pInt = new int(123);
18 char* pStr = new char[20];
19
20 strcpy(pStr, "TestApp");
21 delete pInt;
22
23 // 设置内存快照ms2
24 _CrtMemCheckpoint(&ms2);
25
26 // 比较两个快照, 这里没有释放pStr,应该被捕获到内存泄露
27 if (_CrtMemDifference(&ms3, &ms1, &ms2))
28 {
29 printf("\n Memory leak detected \n");
30 // 输出内存泄露上下文, 默认为vs output窗口。这里输出到控台应用程序窗口中(前面两行代码的重定向)
31 _CrtDumpMemoryLeaks();
32 }
33 else
34 {
35 printf("No memory leak \n");
36 }
37
38 return 0;
39 }
40