首先使用windbg工具gflags.exe设置内存启动跟踪内存泄露进程的user stack
启动方法就是运行下面指令gflags.exe /i test.exe +ust
等价于HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options,命令“gflags.exe /i test.exe +ust”实际上就是在该路径下创建一个子键“test.exe”并创建一个名为GlobalFlag内容为0x00001000的REG_DWORD值。
使用windbg加载test.exe,运行关闭时windbg中会提示内存泄露
normal block at 0x026A5F98, 4000 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object dump complete.
可以发现地址0x026A5F98就是内存泄漏的地址泄漏4000个字节
通过!heap命令对该地址进行分析可以发现具体的调用堆栈
0:000> !heap -p -a 0x026A5F98 address 026a5f98 found in _HEAP @ 14f0000 HEAP_ENTRY Size Prev Flags UserPtr UserSize - state 026a5f60 01fc 0000 [00] 026a5f78 00fc4 - (busy) 77a1b234 ntdll!RtlAllocateHeap+0x00000274 584d7743 MSVCR100D!_heap_alloc_base+0x00000053 584e5d8c MSVCR100D!_heap_alloc_dbg_impl+0x000001fc 584e5b2f MSVCR100D!_nh_malloc_dbg_impl+0x0000001f 584e5adc MSVCR100D!_nh_malloc_dbg+0x0000002c 584e5a91 MSVCR100D!_malloc_dbg+0x00000021 58694dd6 mfc100ud!operator new+0x00000026 58694e6a mfc100ud!operator new[]+0x0000001a 58694768 mfc100ud!operator new[]+0x00000018 *** WARNING: Unable to verify checksum for SendMsgEx.exe 2a3c25 SendMsgEx!CSendMsgExDlg::Thread1Proc+0x00000055 767c1174 kernel32!BaseThreadInitThunk+0x0000000e 779fb3f5 ntdll!__RtlUserThreadStart+0x00000070 779fb3c8 ntdll!_RtlUserThreadStart+0x0000001b
可以发现内存泄漏的地址在CSendMsgExDlg::Thread1Proc这个地址里面调用了new[]导致内存泄漏
DWORD WINAPI CSendMsgExDlg::Thread1Proc(__in LPVOID lpParameter) { INT *pVal = new INT[1000]; //.................. }
如此即可发现导致内存泄漏的原因和地址!