利用VC/VS检测程序内存溢出(转)

VisualC ++ 没有默认启动内存泄露检测,即如果某段代码产生内存溢出也不会在“输出窗口”调试标签下输出内存溢出相关信息

1 )需要手工添加代码检测

#define  _CRTDBG_MAP_ALLOC // 顺序改变后 函数可能无法正常工作

#include 
< stdlib.h >

#include 
< crtdbg.h > // 可以将函数malloc()和free()映射到对应的调试板本的_malloc_dbg,_free_dbg, 该函数会跟踪内存分配和释放

(
2 )添加以上代码后,可以在程序要检测内存泄露的地方加入函数_CrtDumpMemoryLeaks(),来报告内存泄露信息,如下:

#include 
< stdio.h > // printf等函数的包含文件
#define  _CRTDBG_MAP_ALLOC
#include 
< stdlib.h >
#include 
< crtdbg.h >

void  main()
{
int *  iArray = ( int * )malloc( sizeof ( int )); // 动态分配空间
for ( int  i = 0 ;i < 100 ;i ++ )
{
   iArray
= ( int * )realloc(iArray,(i + 1 ) * sizeof ( int ));
   printf(
" %08x " ,( int )iArray);
   iArray[i]
= i + 1 ;
}
for (i = 0 ;i < 100 ;i ++ )
   printf(
" %5d " ,iArray[i]);
_CrtDumpMemoryLeaks();
// 报告内存泄露函数
}

调试后,输出窗口出现

{
153 } normal block at  0x00631B90 400  bytes  long . // 内存溢出信息

对应语句为: iArray
= ( int * )realloc(iArray,(i + 1 ) * sizeof ( int ));

(
3 )设置CRT报告模式

默认下 _CrtDumpMemoryLeaks输出泄露内存信息到“输出窗口”的调试标签,这样较难看出,所以可以用_CrtSetReportMode()进行重置,函数原型:                           int_CrtSetReportMode(
int  reportType, int  reportMode) reportType有_CRT_WARN,_CRT_ERROR,_CRT_ASSERT;

reportMode有_CRTDBG_MODE_DEBUG\\输出信息到调试标签页,

_CRTDBG_MODE_WNDW   \\创建带有中断 重试的信息提示框(建议使用);

和_CRTDBG_MODE_FILE    \\输出信息到指定文件,其中_CrtSetReportFile()函数来定义用户文件


4 )使用_CrtSetDbgFlag    

对于多出口的程序,每个出口位置都使用_CrtDumpMemoryLeaks();
// 报告内存泄露函数将会需要输入很多次,

这时可以使用在程序开始处包含如下语句

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEN_DF,_CRTDBG_LEAK_CHECK_DF)     即如下程序无论从哪退出都可以自动调用_CrtDumpMemoryLeaks();检测.
转自:http://hi.baidu.com/pro_hc/blog/item/dcddc0f2c7d8ef5b342acc2e.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值