CRT 检测内存泄露


  • 定义宏_CRTDBG_MAP_ALLOC_
  • 包含头文件crtdbg.h
  • 调用_CrtDumpMemoryLeaks
  • 需要在Debug模式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#define _CRTDBG_MAP_ALLOC

#include <crtdbg.h>
#include <cstdlib>
#include <iostream>

#define MEMLEAK_REPORT \
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); \
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); \
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); \
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); \
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); \
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); \
_CrtDumpMemoryLeaks();

int main() {
std::cout << "Hello World!\n";
int *x = (int *)malloc(sizeof(int));
*x = 7;
printf("%d\n", *x);
x = (int *)calloc(3, sizeof(int));
x[0] = 0x3F;
x[1] = 0xABCD;
x[2] = 0xDEADBEEF;
printf("%d %d %d\n", x[0], x[1], x[2]);
MEMLEAK_REPORT
}


文章作者: sfc9982
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 sfc9982 !
  目录