VS2005 检测内存泄漏的方法(转载)

时间:2023-03-09 03:33:08
VS2005 检测内存泄漏的方法(转载)

一、非MFC程序可以用以下方法检测内存泄露:

1.程序开始包含如下定义:

  1. #ifdef _DEBUG
  2. #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
  3. #else
  4. #define DEBUG_CLIENTBLOCK
  5. #endif  // _DEBUG
  6. #define _CRTDBG_MAP_ALLOC
  7. #include <stdlib.h>
  8. #include <crtdbg.h>
  9. #ifdef _DEBUG
  10. #define new DEBUG_CLIENTBLOCK
  11. #endif  // _DEBUG

2.程序中添加下面的函数:

  1. _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);

Debug版本程序运行结束后如有内存泄漏,输出窗口中会显示类似信息:

  1. Detected memory leaks!
  2. Dumping objects ->
  3. g:/programs/test/test.cpp(16) : {51} client block at 0x00385C58, subtype 0, 4 bytes long.
  4. Data: <    > CD CD CD CD
  5. Object dump complete.

二、MFC程序内存泄漏检测方法:

1.在 CMyApp 中添加如下三个 CMemoryState 类的成员变量:

  1. #ifdef _DEBUG
  2. protected:
  3. CMemoryState m_msOld, m_msNew, m_msDiff;
  4. #endif  // _DEBUG

2.在 CMyApp::InitInstance() 中添加如下代码:

  1. #ifdef _DEBUG
  2. m_msOld.Checkpoint();
  3. #endif  // _DEBUG

3.在 CMyApp::ExitInstance() 中添加如下代码:

  1. #ifdef _DEBUG
  2. m_msNew.Checkpoint();
  3. if (m_msDiff.Difference(m_msOld, m_msNew))
  4. {
  5. afxDump<<"/nMemory Leaked :/n";
  6. m_msDiff.DumpStatistics();
  7. afxDump<<"Dump Complete !/n/n";
  8. }
  9. #endif  // _DEBUG

Debug版本程序运行结束后如有内存泄漏,输出窗口中会显示类似信息:

  1. Memory Leaked :
  2. 0 bytes in 0 Free Blocks.
  3. 8 bytes in 1 Normal Blocks.
  4. 0 bytes in 0 CRT Blocks.
  5. 0 bytes in 0 Ignore Blocks.
  6. 0 bytes in 0 Client Blocks.
  7. Largest number used: 8825 bytes.
  8. Total allocations: 47506 bytes.
  9. Dump Complete !
  10. Detected memory leaks!
  11. Dumping objects ->
  12. g:/programs/chat/chatdlg.cpp(120) : {118} normal block at 0x00D98150, 8 bytes long.
  13. Data: <        > A8 7F D9 00 01 00 00 00
  14. Object dump complete.
VS2005 检测内存泄漏的方法(转载)

本文转自:http://ufownl.blog.163.com/blog/static/1250122200861912757566/

http://blog.csdn.net/wangningyu/article/details/4465229