多線程中CString記憶體流失的解決方案。

來源:互聯網
上載者:User

多線程導致的記憶體流失
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,也可以避免
記憶體流失。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.