vs2010
第一步:
#include <stdlib.h>
#include <crtdbg.h>int main()
{
#ifdef _DEBUG
//_crtBreakAlloc = 0;
#endif
char *malloc_s = (char*)malloc(1);
for (int i = 0; i < 10; i++)
{
free(malloc_s);
malloc_s = (char*)malloc(1);
}
_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
return 0;
}
在debug下运行(F5)上面代码,
OUTPUT中
hello1.exe': Loaded 'C:\Windows\System32\KernelBase.dll', Cannot find or open the PDB file
'hello1.exe': Loaded 'C:\Windows\System32\msvcr100d.dll', Symbols loaded.
Detected memory leaks!
Dumping objects ->
{97} normal block at 0x004E5898, 1 bytes long.
Data: < > CD
Object dump complete.
The program '[1068] hello1.exe: Native' has exited with code 0 (0x0).
97 即为 内存泄露地址
第二步:
#include <stdlib.h>
#include <crtdbg.h>int main()
{
#ifdef _DEBUG
_crtBreakAlloc = 97;
#endif
char *malloc_s = (char*)malloc(1);
for (int i = 0; i < 10; i++)
{
free(malloc_s);
malloc_s = (char*)malloc(1);
}
_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
return 0;
}
在debug下运行(F5)上面代码,在 call stack中
hello1.exe!wmain(int argc, wchar_t * * argv) Line 17 + 0xa bytes C++
回车
定位到内存泄露位置即第几个循环。
在vs2011中
第一步
在主函数返回处加个断点
#include "stdafx.h"
#include <stdlib.h>
#include <crtdbg.h>
int main()
{
#ifdef _DEBUG
//_crtBreakAlloc = 64;
#endif
char *malloc_s = (char*)malloc(1);
for (int i = 0; i < 10; i++)
{
free(malloc_s);
malloc_s = (char*)malloc(1);
//a
}
_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
return 0;
}
在debug下(F5)运行
在 immediate window中查看
{64} normal block at 0x002C6718, 1 bytes long.
Data: < > CD
Object dump complete.
Detected memory leaks!
Dumping objects ->
{64} normal block at 0x002D6718, 1 bytes long.
Data: < > CD
Object dump complete.
64即为内存泄露地址处
第二部
#include "stdafx.h"
#include <stdlib.h>
#include <crtdbg.h>
int main()
{
#ifdef _DEBUG
_crtBreakAlloc = 64;
#endif
char *malloc_s = (char*)malloc(1);
for (int i = 0; i < 10; i++)
{
free(malloc_s);
malloc_s = (char*)malloc(1);
//a
}
_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
return 0;
}
在debug下运行(F5)
在call stack (调试--窗口--call stack)中
> Hello.exe!main() Line 19 C++
回车
定位到内存泄露位置及第几行泄露