zoukankan      html  css  js  c++  java
  • 多线程中CString内存泄漏的解决方法。


    多线程导致的内存泄漏
    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,也可以避免
    内存泄漏。

  • 相关阅读:
    js 笔记
    openstack笔记
    Nginx
    Nginx
    Nginx
    nginx 服务器篇
    Nginx 原理篇
    MySQL 视图、触发器、函数、存储过程
    day41
    MySQL 作业题及答案
  • 原文地址:https://www.cnblogs.com/yuzhould/p/4454991.html
Copyright © 2011-2022 走看看