zoukankan      html  css  js  c++  java
  • 关于DLL工程中存在全局变量可能导致MFC内存泄露误报的原因分析及解决办法

    作者:朱金灿

    来源:http://blog.csdn.net/clever101

     

            之前遇到过一次VS 2008内存泄露误报事故,详见:《坑爹的VS2008内存泄露报告》。目前据我所知,在使用boost库和osg库都存在此种内存泄露误报问题。今天从网上找到了一个英文帖子:Whydoes my OSG MFC based application show memory leaks,正是对这种内存泄露误报的原因的很好的解释。

     

    帖子摘要如下:

     

    There is a known issue/BUG with MFC, were MFCmakes a call to
    _CrtDumpMemoryLeaks() in the destructor of the_AFX_DEBUG_STATE, followed by _CrtSetDbgFlag() which sets it to~_CRTDBG_LEAK_CHECK_DF (therefor disabling memory leak test at *true* programexit) This destructor is called at exit (i.e. atexit()), but before staticsresiding in dlls and others are destroyed, resulting in many false memory leaksare reported

    As to fix any real memory leaks, you have the source ...also you can do a
    google to see how others have gotten around this issue toget at any real
    leaks.

    The MFC memory leak will not go away as Microsoft have noreason to fix it( it been there for many years) as MFC is a deprecated API asfar as they are concerned。

     

            实际上这个帖子说得还不是很直白,之前搜到的原因说得更清楚:

             MFC dumps leaks prematurely whenit exits, instead of waiting for the  
    CRT to dump leaks following static data destruction, and this causes  
    spurious leak reports for objects which allocated memory before MFC  
    was initialized and which thus are destroyed after MFC exits. This is  
    commonly observed when using the MFC DLL in a program that also uses  
    the C++ runtime DLL.

     

            综合上面两种说法就是:这是MFC的一个著名bug,就是当MFC dll退出时,就会误认为一些还没释放的对象存在内存泄露,问题在于这些对象(一般是一些dll的全局对象)一般是在MFCdll卸载后才释放。因此一个解决思路是确保程序首先加载MFC dll,最后卸载MFC dll。具体办法是:

          

            在你的主调用工程(一般是一个exe工程),在工程属性作如下修改:

     

    1. MFC的使用中从原来的“在共享DLL使用MFC”改为“使用标准Windows库”,如下图:

    2. 增加预处理器:_AFXDLL,如下图


    3. 在附件依赖项中增加MFC库,具体填哪个MFC库根据你的情况而定,如多字节字符集下debug编译,就填mfc90d.lib ( VS2008环境下),其它的据情况选择mfc90.lib、mfc90ud.lib或mfc90u.lib。如下图:




          如果你觉得我的博客对你有帮助,请在下面网址中博客之星评选活动投我一票:

    http://vote.blog.csdn.net/item/blogstar/clever101(单击候选人介绍下面的投他一票那个按钮)

    参与投票有机会获奖:

         最佳贡献奖:通过微博分享活动就有机会获得30元充值卡一张(每周抽选5名)
        幸运奖:凡参与投票用户就有机会获得精美小礼品一份。(每周抽选5名)
        积极参与奖:所有参与投票并符合条件的用户均可获得20个下载积分。



  • 相关阅读:
    .NET平台下,初步认识AutoMapper
    python 二分查找算法
    01背包问题(动态规划)python实现
    NSSM安装服务
    iis .apk .ipa下载设置
    动态规划 转载
    leetcode 5 查找最长的回文子串
    [DEncrypt] MySecurity--安全加密/Base64/文件加密 (转载)
    [DEncrypt] HashEncode--哈希加密帮助类 (转载)
    [DEncrypt] Encrypt--加密/解密/MD5加密 (转载)
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6470736.html
Copyright © 2011-2022 走看看