VisualStudio C++内存泄漏的检测方法

代码

#define _CRTDBG_MAP_ALLOC
#include <iostream>
#include <crtdbg.h>
using namespace std;
void test1() {
	int* p = new int[10];
        //int* p = (int*)malloc(sizeof(int) * 10);
}
void test2() {
	int *p = new int[20];
        //int* p = (int*)malloc(sizeof(int) * 20);
}
int main() {
	test1();
	test2();
        _CrtDumpMemoryLeaks();

	return 0;
}

crtdbg头文件

  1. 添加头文件#include <crtdbg.h>

  2. 在程序退出前,也就是main函数return前,加上_CrtDumpMemoryLeaks()函数

  3. 显示结果1,使用new,使用#define _CRTDBG_MAP_ALLOC与否都一样

  4. 显示结果2,使用malloc,不使用#define _CRTDBG_MAP_ALLOC

  5. 显示结果3,使用malloc,使用#define _CRTDBG_MAP_ALLOC,会显示内存泄漏出在哪一行代码

自带快照功能

  1. 加断点
  2. 启用堆分析
  3. F10或F11逐步或逐过程运行,每一步都截取快照

Linux下可以使用valgrind工具

  1. 用-g参数正常编译输出文件
  2. 使用valgrind --leak-check=full ./a.out运行程序,程序退出后会显示内存泄漏信息。(图为引用)
posted @ 2020-12-30 20:54  肥斯大只仔  阅读(578)  评论(0编辑  收藏  举报