您的位置:首页 > 其它

MFC内存泄露检测

2015-08-18 17:23 288 查看
转自: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: