2016-04-23 89 views
-1

我有一個功能,在我的代碼中使用了一百萬次,並且有一個內存泄漏。如何避免內存泄漏與返回const char *

需要輸入const wchar_t*作爲輸入,並返回const char*。 現在我明白這個指針返回(const char*)將需要從調用函數中獲得一個明確的delete[](但我買不起),因爲這意味着我需要在所有位置更改它。

的代碼是這樣的:

inline const char * W2N(const wchar_t* wstr) 
{ 
    int cw=lstrlenW(wstr); 

    if (cw==0) 
    { 
     CHAR *psz=new CHAR[1]; *psz='\0'; return psz; 
    } 

    int cc=WideCharToMultiByte(CP_ACP,0,wstr,cw,NULL,0,NULL,NULL); 
    if (cc==0) return NULL; 

    CHAR *psz=new CHAR[cc+1]; 
    cc=WideCharToMultiByte(CP_ACP,0,wstr,cw,psz,cc,NULL,NULL); 
    if (cc==0) 
    { 
     delete[] psz; return NULL; 
    } 

    psz[cc]='\0'; 
    return psz; 
} 

有什麼,我可以解決這個功能做,以避免內存泄漏。

+0

同意tobi303,但psz返回的指針最終導致泄漏,因爲它從來沒有被釋放。 –

+0

你知道客戶端調用函數什麼時候會用'W2N()'返回的內存完成嗎? – quamrana

+3

爲什麼不使用'std :: string'而不是'char *'? – Barmar

回答

2

您可以並且應該將指針包裹在std::unique_ptr<char[]>之內。這將以一種慣用的C++方式解決你確切的問題。

這將改變你的函數是這樣的:

inline std::unique_ptr<char[]> W2N(const wchar_t *wstr) { 
    int cw = lstrlenW(wstr); 

    if(cw == 0) { 
     auto psz = std::make_unique<char[]>(1); 
     psz[0] = '\0'; 
     return psz; 
    } 
    int cc = WideCharToMultiByte(CP_ACP, 0, wstr, cw, NULL, 0, NULL, NULL); 
    if(cc == 0) 
     return nullptr; 
    auto psz = std::make_unique<char[]>(cc + 1); 
    cc = WideCharToMultiByte(CP_ACP, 0, wstr, cw, psz, cc, NULL, NULL); 
    if(cc == 0) { 
     return nullptr; 
    } 
    psz[cc] = '\0'; 
    return psz; 
} 

這當然,假定您可以訪問一個C++ 14兼容的編譯器(用於std::make_unique),或至少C++ 11兼容(對於std::unique_ptr)。

當然,如評論中所述,您可以返回std::string。如果你這樣做,請注意從函數返回nullptrNULL可能會出現段錯誤。