使用EXIT(0) 直接退出後,出現記憶體洩露情況
使用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);
}
}