mfc下報OSG內存泄漏解決方法

 

osgMFC例子 VS2005報內存泄露的解決方法

首先感謝 Email列表裏面的牛人,是他們幫我找到了解決方法,見下面網頁
http://www.vis-sim.com/3dsceneBB/viewtopic.php?t=1027

其內容摘抄如下:
There is a known issue/BUG with MFC, were MFC makes 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* program exit) This destructor is called at exit (i.e. atexit()), but before statics residing in dlls and others are destroyed, resulting in many false memory leaks are reported

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

上面大體意思就是 因爲 微軟的VS2005編譯器在最後程序退出時的步驟裏,診斷是否有內存泄露的dll並不一定是最後卸載的 ,這就造成了如果有其他dll在它之後卸載,那麼裏面的static對象就會被認爲是沒有釋放,而OSG裏面有很多 static這種對象,因此纔會出現一大串內存泄露消息。
下面是解決方案,牛人提了3 種 ,但是他親自只試了一種,我也是這麼做的:

Another solution to the MFC and wrong memory leak reports. You need to make your MFC dll load first during application start up and unload last during application exit. I managed to do this by making the following change.
儘可能讓微軟的 dll最後卸載,因此有時候需要人爲的把微軟的dll配置在首先加載,最後卸載的位置
In your MFC application.

. Goto project settings. In there, make the following changes for theDebug build.  到工程設置
. General->Use of MFC->Use Standard Windows Libraries.                             找到 配置屬性->常規->MFC的使用 設置爲"使用標準Windows庫"
. Add _AFXDLL to C/C++->Preprocessor->Preprocessor Definitions.                    在c/c++ ->預處理器 裏面的預處理器定義裏面加入 _AFXDLL
. Add mfc80??.lib (in my case it is mfc80ud.lib) as a first dependency or at least before osg libs to Linker->Input->Additional
Dependencies.          在鏈接器->輸入->附加依賴項 裏面的開始位置加入VS的庫,這些庫在VS2005的安裝目錄下面的 VC/atlmfc/lib,我個人加了 mfc80d.lib 和 mfcm80d.lib

You can find what the other mfc libs are in your visual studio install directory/VC/atlmfc/lib. You don't need to do this release mode.  
Release模式下就不需要這麼做了

其他的解決方法:設置爲共享DLL 但是要建立MFC的 dll與osgdll的依賴關係,實際上還是想讓 osg的 dll都卸載完 再卸載MFC的dll
If you add a MFC dependency to osg dlls that should also create the desired effect. Change the Use of MFC setting to General->Use of
MFC->Use MFC In a Shared DLL in your debug builds of osg libraries.
This should add MFC dll dependency to your osg dll in debug so forcing MFC dll to unload after the osg dlls but as I said I did not actually
try this.
還有:
Rebuild the MFC dlls with the following change. At least remove the "_CrtDumpMemoryLeaks()" call in
_AFX_DEBUG_STATE's destructor. It is in VS_INSTALL/VC/atlmfc/src/mfc/dumpinit.cpp. The makefile is in VS_INSTALL/VC/atlmfc/src/atlmfc.mak. I did not try this, either. 重新編譯 VS的dll

我測試的項目是osg2.4的源碼裏的 osgMFC 和  論壇裏的一個osgMFC的例子,名字叫 RambleSystem, 這兩個例子 按照第一種方法的步驟設置完後,都沒有內存泄露了, 另外這兩個例子是 通過線程實現的 ,我又測試了一個不用線程,而是通過在MFC視圖類的 OnDraw方法,不斷DoFrame來實現的 osgMFC的例子,結果也沒有內存泄露。
發佈了29 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章