使用C Run-Time库自带的内存泄漏检测APIs
1.建立debug_redefine_new.h文件
#ifndef SET_DEBUG_NEW_H
#define SET_DEBUG_NEW_H
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
#endif // end SET_DEBUG_NEW_H
该文件只能再*cpp文件中引用,原理就是替换new、添加行号,这样就能够定位具体内存泄露的位置。
2.在cpp文件引用debug_redefine_new.h
#include "debug_redine_new.h"
3.在main.cpp文件中添加_CrtSetDbgFlag 开启检测
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
AUTClient w;
w.show();
//_CrtSetBreakAlloc(180);
char* pChars = (char*)new(char[10]) ;
//delete(pChars);
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
return a.exec();
}
4.运行结果
main.cpp(30) : {3732} client block at 0x0000021745507590, subtype 0, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
{3702} normal block at 0x0000021745507130, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
5.通过定位_CrtSetBreakAlloc中断在没有释放的内存分配
_CrtSetBreakAlloc(3732);
VLD检测内存泄露
1.下载并安装VLD
vld 下载链接 https://kinddragon.github.io/vld/
vld 源码 https://github.com/KindDragon/vld
2.vs工程下添加头文件与连接库路径,并添加vld.lib连接库
3.main函数中添加#include <vld.h> 头文件
4.如果是动态库在dllmain.cpp中添加#include <vld.h>
总结
include <crtdbg.h>与include <vld.h>都只能再debug下使用,都是通过重写malloc,free等函数或重载new,delete运算符,是侵入式的,对第三方库的内存泄露无能为力。
介绍两款检测内存泄露工具:Process Explorer; Bear。