转自: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
#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