window下调试C++内存泄漏的几种方法

  1. 环境: Windows10,VS2019, Qt5.9.7, C++11
  2. 目的: 定位内存泄漏问题,并解决

1. VS2019自带的诊断工具,可在程序运行时打开诊断工具窗口-----》勾选内存使用率----》启用堆栈快照

类型视图能根据各种差异,点击左侧箭头所指的视图实例,可准确定位内存泄漏发生点。

2. windows CRT调试(Find memory leaks with the CRT library)

官方有详细使用描述:官网链接:

我简单描述:

方式1:

// debug_new.cpp
// compile by using: cl /EHsc /W4 /D_DEBUG /MDd debug_new.cpp
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>

#ifdef _DEBUG
    #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
    // Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
    // allocations to be of _CLIENT_BLOCK type
#else
    #define DBG_NEW new
#endif

struct Pod {
    int x;
};

void main() {
    Pod* pPod = DBG_NEW Pod;
    pPod = DBG_NEW Pod; // Oops, leaked the original pPod!
    delete pPod;

    _CrtDumpMemoryLeaks();//直接打印内存泄漏信息
}

方式2:

//#ifdef _DEBUG
//#define  DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
//#else
//#define  DEBUG_CLIENTBLOCK
//#endif
//#define _CRTDBG_MAP_ALLOC
//#include <stdlib.h>
//#include <crtdbg.h>
//#ifdef _DEBUG
//#define  new DEBUG_CLIENTBLOCK
//#endif

//_CrtMemState s1,s2,s3;

//_CrtMemCheckpoint(&s1);//记录s1处内存数据
//to do something
//_CrtMemCheckpoint(&s2);//记录s1处内存数据

//if (_CrtMemDifference(&s3, &s1, &s2))
//	_CrtMemDumpStatistics(&s3);//内存泄漏,两处内存数据不一致,差异结果返回至s3,打印信息

3. VLD(Visual Leak Detector)

仅适用于vc++,Enhanced Memory Leak Detection for Visual C++,相当好用,如果你也是msvc编译项目,强烈推荐此方式,仅需要在使用的项目中任一文件处包含其“vld.h”头文件即可,调试时会比较卡顿,另外需要在项目属性中添加vld头文件、库文件所在路径,按理说应该在环境变量中添加这两处路径就应该可以全局使用,但是我试验过并不能行,不知为何。。。

成功加载后,在程序运行时可以看到打印信息提示加载vld库,关闭程序后调试窗口打印内存泄漏等信息。

官网:

4. 养成良好的c++编码习惯,合理使用c++11及以上提供的智能指针、合理利用RAII机制

5. 转行。。。

经验分享 程序员 微信小程序 职场和发展