MFC内存泄露检测

转自:http://blog.sina.com.cn/s/blog_62d15fb60100y0h8.html


今天整理evernote,发现好多年前的零碎记录


_CrtDumpMemoryLeaks()函数能显示当前情况下的内存泄露,调用该函数的时候,凡是当前状态下没有销毁的对象,没有释放的空间,都被判定为泄露,调用需在StdAfx.h中添加如下代码:



#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include<stdlib.h>
#include<crtdbg.h>
#endif


则在debug模式下,程序运行到 _CrtDumpMemoryLeaks 时,在debug的输出框会出现类似如下信息:



Detected memory leaks!
    Dumping objects ->
    D:...*****.cpp(1463) : {8244} normal block at 0x01AA84B8, 512 bytes long.
    Data: <                > 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

上述信息提示检测到内存泄露发生的具体的文件名及行号,后面则给出了内存泄露的标号、大小及内容。

MFC自带的内存快照能够很方便的检测内存泄露的问题。在MSDN中提供了使用的代码
请注意内存检查语句由 #ifdef _DEBUG / #endif块括起来,以便它们只在程序的 Win32“Debug”版本中被编译。
// Declare the variables needed
#ifdef _DEBUG
   CMemoryState oldMemState, newMemState, diffMemState; //申明CMemoryState对象
   oldMemState.Checkpoint();//添加内存检测标记,获取测试块运行前的内存大小
#endif
  
// Do your memory allocations and deallocations.
   CString s("This is a frame variable");
   // The next object is a heap object.
  CPerson* p = new CPerson( "Smith", "Alan", "581-0215" );

#ifdef _DEBUG
   newMemState.Checkpoint(); //添加内存检测标记,获取测试块运行后的内存大小
   if( diffMemState.Difference( oldMemState, newMemState ) ) //比较前后的内存变化,如果泄露则返回真值
   {
           diffMemState.[ft=rgb(0, 0, 0),2,consolas, courier, monospace]DumpStatistics();//统计 前后内存变化情况
}
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值