windows 内存泄漏检测工具之 VLD
VLD(Visual Leak Detector)内存泄漏一直是一个令人头疼的问题,Visual Leak Detector工具在处理内存泄漏时非常好用,简单介绍一下Visual Leak Detector。
Visual Leak Detector是一个开源的,免费的,健壮的又使用起来很简单的内存泄漏检测系统,支持vs2008-vs2015,支持C和C++的工程。
下载地址:https://archive.codeplex.com/?p=vld
原理
1.远程注入DLL到目标进程(VLD是需要目标进程链接DLL的),关键部分就是这个DLL中的逻辑
2.当DLL被加载目标进程的时候,HOOK内存分配释放函数。当程序分配内存的时候,记录下这次分配的信息(分配的位置,大小,调用堆栈等)到一个map中,当程序释放内存的时候,就从map中移除。
3.在进程退出或者某个时候,可以遍历map,打印出还没有被释放的内存块的信息。
上面只是一个简单的描述,具体的话涉及的问题还比较多,当然资料也很多。
远程注入:关键点CreateRemoteThread
HOOK:HOOK有现成库detours,minihook等
调用堆栈:可以使用DbgHelp相关的函数来加载pdb,解析堆栈StackWalk64
使用步骤
现在的最新版是2.5.1,下载完成之后直接一键安装,安装的时候会提示是否要配置vs,勾选的话,安装过程会直接配置好vs和path环境变量。
使用起来只需要简单的在工程中加入:
#include <vld.h>
在项目的属性设置需要如下操作
打开安装路径下的vld.ini文件,将ReportTo设置为both,为了在非bebug下也能看到检测结果,注意文件的写入权限,不然不可以写入。
源码
#include "stdafx.h"
#include <stdlib.h>
#include <vld.h>
int _tmain(int argc, _TCHAR* argv[])
{
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
delete pp;
system("pause");
return 0;
}
如果是release模式,需要设置其他操作,请参考《使用VLD进行内存泄漏检测(release + debug)》https://blog.csdn.net/xiaomucgwlmx/article/details/87630671
结果分析
Visual Leak Detector Version 2.5.1 installed.
Outputting the report to the debugger and to C:\Users\Administrator\Documents\Visual Studio 2013\Projects\MemeryDemo\Debug\memory_leak_report.txt
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 1 at 0x0085AF60: 1 bytes ----------
Leak Hash: 0x2C875C8E, Count: 1, Total 1 bytes
Call Stack (TID 6308):
MSVCR120D.dll!operator new()
c:\users\administrator\documents\visual studio 2013\projects\memerydemo\memerydemo\memerydemo.cpp (10): MemeryDemo.exe!wmain() + 0x7 bytes
f:\dd\vctools\crt\crtw32\dllstuff\crtexe.c (466): MemeryDemo.exe!wmainCRTStartup()
kernel32.dll!BaseThreadInitThunk() + 0x12 bytes
ntdll.dll!RtlInitializeExceptionChain() + 0x63 bytes
ntdll.dll!RtlInitializeExceptionChain() + 0x36 bytes
Data:
00 ........ ........
---------- Block 3 at 0x0085AFC8: 10 bytes ----------
Leak Hash: 0x7A9AFC72, Count: 1, Total 10 bytes
Call Stack (TID 6308):
MSVCR120D.dll!malloc()
c:\users\administrator\documents\visual studio 2013\projects\memerydemo\memerydemo\memerydemo.cpp (12): MemeryDemo.exe!wmain() + 0xA bytes
f:\dd\vctools\crt\crtw32\dllstuff\crtexe.c (466): MemeryDemo.exe!wmainCRTStartup()
kernel32.dll!BaseThreadInitThunk() + 0x12 bytes
ntdll.dll!RtlInitializeExceptionChain() + 0x63 bytes
ntdll.dll!RtlInitializeExceptionChain() + 0x36 bytes
Data:
CD CD CD CD CD CD CD CD CD CD ........ ........
Visual Leak Detector detected 2 memory leaks (83 bytes).
Largest number used: 129 bytes.
Total allocations: 129 bytes.
Visual Leak Detector is now exiting.
运行程序结束后,工程路径下生成一个“memory_leak_report.txt”文件,打开之后可以看到。
上面检测出两处内存泄漏,分别是12行和10行,中间new出来的数组使用delete释放和CRT一样检测结果,都没有正确检测出来。
优点
支持windows的debug和release模式,并且32和64位都支持。
缺点
不支持mingw编译器
对于new的数组也不能正确检测
需要对源码进行少量修改以及项目配置