您的位置:首页 > 其它

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

2012-09-02 19:14 1236 查看
作者:朱金灿

来源: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。如下图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐