定位C++内存泄露位置

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++

回车 

定位到内存泄露位置及第几行泄露


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值