MFC内存泄露

来源:互联网 发布:软件测试行业学费 编辑:程序博客网 时间:2024/05/16 01:24

 之前遇到过一次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。如下图:

0 0
原创粉丝点击