内存泄露的检测方式非常多,因此在这里指介绍一种最简单的内存泄露检测工具。
VLD(Visual Leak Detector)
使用方法
#include <vld.h>
只要在公共的头文件中添加这一句代码就行。
F5调试运行才能在OutPut窗口中显示内存泄露的信息。
ps:
当然还要配置环境,让工程能够找到头文件和LIB文件
可能有疑问什么时候加载LIB文件的,在vld.h文件中可以看到
#pragma comment(lib, "vld.lib")
这样就没问题了吧!
还有个问题,什么时候VLD有效?
可以看到vld.h文件有一个宏
#if defined _DEBUG || defined VLD_FORCE_ENABLE
可以看到_DEBUG宏表示DEBUG模式下生效
还有在其他模式下只要定义VLD_FORCE_ENABLE,VLD也会生效。
VLD链接
VLD的官网和下载地址:http://vld.codeplex.com/
例子
int _tmain(int argc, _TCHAR* argv[])
{
int *p = new int;
return 0;
}
例如,
new一个int型的数据,然后不delete。
使用工具检测的结果,在OutPut窗口中可以看到。
Visual Leak Detector Version 2.2.3 installed.
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 1 at 0x00A74008: 4 bytes ----------
Call Stack:
c:\users\administrator\desktop\mdxkernel_201407081724\vld_sample\vld_sample.cpp (9): vld_sample.exe!wmain + 0x7 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (552): vld_sample.exe!__tmainCRTStartup + 0x19 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (371): vld_sample.exe!wmainCRTStartup
0x7651336A (File and line number not available): kernel32.dll!BaseThreadInitThunk + 0x12 bytes
0x77699F72 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0x63 bytes
0x77699F45 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0x36 bytes
Data:
CD CD CD CD ........ ........
Visual Leak Detector detected 1 memory leak (40 bytes).
Largest number used: 40 bytes.
Total allocations: 40 bytes.
Visual Leak Detector is now exiting.
结果描述:
监测到一处泄露,泄露的大小为4Byte,泄露内存的内容是CD CD CD CD。
还有一个就是内存泄露的堆栈,双击堆栈就可以跳转到代码的具体位置。