使用EXIT(0) 退出程式時,跳出以下記憶體泄露資訊:
Detected memory leaks!
Dumping objects ->
f:\sp\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {178} normal block at 0x003DA9B0, 36 bytes long.
Data: < 9Px > AC 39 50 78 09 00 00 00 09 00 00 00 01 00 00 00
f:\sp\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {177} normal block at 0x003DA900, 110 bytes long.
Data: < 9Px. . > AC 39 50 78 2E 00 00 00 2E 00 00 00 01 00 00 00
Object dump complete.
二者都是字串問題 ,猜測是由於CString引起的
但是為什麼CString會引起呢?
來源程式如下:
{CString setPath=L"f:\\";g_strIP=L"127.0.0.1";CLoginDlg dlg;dlg.m_strIP = g_strIP; // m_strIP是dlg的CString變數 g_strIP是全域CString變數if (dlg.DoModal()==IDOK){g_strIP = dlg.m_strIP;}else{exit(0);}}
分析:
此段程式有兩個局部變數
CString setPath
CLoginDlg dlg;
及一個全域變數CString g_strIP
其中局部變數dlg中,包含字串變數 dlg.m_strIP
CSting 在堆上開闢空間 預設情況下,出了範圍後,CString對象是自動撤銷的。
但是,由於使用了EXIT(0) ,強行退出這段範圍, 因此在這段範圍中使用的CString對象沒有得到釋放,故而出現了記憶體泄露情況。
而全域CString對象則不受此影響,在EXIT(0) 退出函數中,會自動釋放全域CString
因此,導致記憶體泄露的元兇即為 範圍之內的CString局部變數。 既然不能自動撤銷,那隻好人為撤銷了,在強行退出前,添加CString撤銷語句即可消除記憶體泄露。
修改後的程式如下:
{CString setPath=L"f:\\";g_strIP=L"127.0.0.1";CLoginDlg dlg;dlg.m_strIP = g_strIP; // m_strIP是dlg的CString變數 g_strIP是全域CString變數if (dlg.DoModal()==IDOK){g_strIP = dlg.m_strIP;}else{dlg.m_strIP.Empty(); //撤銷局部CSTRING對象setPath.Empty();exit(0);}}