多線程導致的記憶體流失
DWORD WINAPI ConnectionWorkerProc(LPVOID pObject)
{
CString strPath;
CString strFileName;
CString currentStr;
TCHAR currentPath[512] = _T("");
TCHAR sendPfilePath[256] = _T("");
GetCurrentDirectory(sizeof(currentPath), currentPath);
strPath=CString(currentPath);
currentStr=CString(currentPath);
strFileName=strPath + strFileName;
CString strTest;
char test[30] = "sasdsdsaasd";
strTest = CString(test);
while{
Sleep(30);
}
}
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {1500} normal block at
0x01A7D220, 40 bytes long.
Data: <, x > 2C FB BF 78 0B 00 00 00 0B 00 00 00 01 00 00 00
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {1498} normal block at
0x01A7E340, 46 bytes long.
Data: <, x > 2C FB BF 78 0E 00 00 00 0E 00 00 00 01 00 00 00
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {1497} normal block at
0x01A7DAB8, 46 bytes long.
Data: <, x > 2C FB BF 78 0E 00 00 00 0E 00 00 00 01 00 00 00
f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {1496} normal block at
0x01A7CCD0, 46 bytes long.
一直到程式運行結束,線程函數都沒有結束,在棧上沒有彈出,導致了記憶體流失。
在轉化和賦值的過程,CString內部分配了記憶體,但是由於該函數一直沒有執行結束,CString內部申請的
記憶體便一直沒有釋放掉。
解決的方法:
1,當知道線程有可能或者確定不會結束,不要線上程中使用CString的copy,assignment,add,使用TCHAR
或者char的,strcat,strcpy等,或者使用std::string,也不會造成記憶體流失
2,使用CString的時候,new和delete,CString *pStr = new CString;用完了之後delete,也可以避免
記憶體流失。