<div>
原文地址: http://ufownl.blog.163.com/blog/static/1250122200861912757566/
非MFC程序可以用以下方法检测内存泄露:
1.程序开始包含如下定义:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
2.程序退出前添加下面的函数:
_CrtDumpMemoryLeaks();
Debug版本程序运行结束后如有内存泄漏,输出窗口中会显示类似信息:
Detected memory leaks!
Dumping objects ->
e:/microsoft visual studio 8/vc/include/crtdbg.h(1150) : {48} normal block at 0x00382F50, 12 bytes long.
Data: < > 01 00 00 00 02 00 00 00 03 00 00 00
Object dump complete.
MFC程序内存泄漏检测方法:
1.在 CMyApp 中添加如下三个 CMemoryState 类的成员变量:
#ifdef _DEBUG
protected:
CMemoryState m_msOld, m_msNew, m_msDiff;
#endif // _DEBUG
2.在 CMyApp::InitInstance() 中添加如下代码:
#ifdef _DEBUG
m_msOld.Checkpoint();
#endif // _DEBUG
3.在 CMyApp::ExitInstance() 中添加如下代码:
#ifdef _DEBUG
m_msNew.Checkpoint();
if (m_msDiff.Difference(m_msOld, m_msNew))
{
afxDump<<”/nMemory Leaked :/n”;
m_msDiff.DumpStatistics();
afxDump<<”Dump Complete !/n/n”;
}
#endif // _DEBUG
Debug版本程序运行结束后如有内存泄漏,输出窗口中会显示类似信息:
Memory Leaked :
0 bytes in 0 Free Blocks.
8 bytes in 1 Normal Blocks.
0 bytes in 0 CRT Blocks.
0 bytes in 0 Ignore Blocks.
0 bytes in 0 Client Blocks.
Largest number used: 8825 bytes.
Total allocations: 47506 bytes.
Dump Complete !
Detected memory leaks!
Dumping objects ->
g:/programs/chat/chatdlg.cpp(120) : {118} normal block at 0x00D98150, 8 bytes long.
Data: < > A8 7F D9 00 01 00 00 00
Object dump complete.