首页 > 代码库 > VS2005 检测内存泄漏的方法(转载)
VS2005 检测内存泄漏的方法(转载)
一、非MFC程序可以用以下方法检测内存泄露:
1.程序开始包含如下定义:
[cpp] view plain copy print?
- #ifdef _DEBUG
- #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
- #else
- #define DEBUG_CLIENTBLOCK
- #endif // _DEBUG
- #define _CRTDBG_MAP_ALLOC
- #include <stdlib.h>
- #include <crtdbg.h>
- #ifdef _DEBUG
- #define new DEBUG_CLIENTBLOCK
- #endif // _DEBUG
2.程序中添加下面的函数:
[cpp] view plain copy print?
- _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
Debug版本程序运行结束后如有内存泄漏,输出窗口中会显示类似信息:
[cpp] view plain copy print?
- Detected memory leaks!
- Dumping objects ->
- g:/programs/test/test.cpp(16) : {51} client block at 0x00385C58, subtype 0, 4 bytes long.
- Data: < > CD CD CD CD
- Object dump complete.
二、MFC程序内存泄漏检测方法:
1.在 CMyApp 中添加如下三个 CMemoryState 类的成员变量:
[cpp] view plain copy print?
- #ifdef _DEBUG
- protected:
- CMemoryState m_msOld, m_msNew, m_msDiff;
- #endif // _DEBUG
2.在 CMyApp::InitInstance() 中添加如下代码:
[cpp] view plain copy print?
- #ifdef _DEBUG
- m_msOld.Checkpoint();
- #endif // _DEBUG
3.在 CMyApp::ExitInstance() 中添加如下代码:
[cpp] view plain copy print?
- #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版本程序运行结束后如有内存泄漏,输出窗口中会显示类似信息:
[cpp] view plain copy print?
- 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.
本文转自:http://ufownl.blog.163.com/blog/static/1250122200861912757566/
http://blog.csdn.net/wangningyu/article/details/4465229
VS2005 检测内存泄漏的方法(转载)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。