现在的位置: 首页 > 综合 > 正文

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

2012年10月01日 ⁄ 综合 ⁄ 共 1410字 ⁄ 字号 评论关闭
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 0x00631B90400 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

 

抱歉!评论已关闭.