C++内存泄露检查

参考自:

http://blog.csdn.net/windows_nt/article/details/8652191
详细解释参考:
http://blog.csdn.net/caowei880123/article/details/7876097

使用:

调试下运行程序,退出后,如果有内存泄露则会在输出窗口得到:
Detected memory leaks!
Dumping objects ->
{58} normal block at 0x00341A38, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
Object dump complete.

配置:
非MFC程序可以用以下方法检测内存泄露:
  1. 程序开始包含如下定义:
    //malloc memory leak detect  
    //
     #define_CRTDBG_MAP_ALLOC  
     #include<stdlib.h>  
     #include<crtdbg.h>  
    //new memory leak detect   
    //  //重新定义new,标记位置 是的输出内存泄露时能打印文件和行号
     #define new  new(_NORMAL_BLOCK, __FILE__, __LINE__)   

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

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);

注意:上面的宏必须包含的每一个要检查泄露的文件中,可以写成一个公共的头文件来包含


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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值