它会导致内存泄漏吗?

时间:2011-01-27 18:09:12

标签: c++ windows memory memory-leaks

我写了这段代码:

string getWinTitle(HWND hwnd){
const int MAX_LENGTH = 1000;
wchar_t title[MAX_LENGTH];
ZeroMemory(title, MAX_LENGTH);
GetWindowText(hwnd, (LPWSTR)title, MAX_LENGTH);
char* buffer = new char[MAX_LENGTH];
wcstombs(buffer, title, MAX_LENGTH);
string res = buffer;
return res;
}

这里有内存泄漏吗? 我是否需要释放ZeroMemory分配的内存? 我是否需要显式释放为缓冲区分配的内存?

谢谢

1 个答案:

答案 0 :(得分:9)

您需要delete [] buffer;,因为它已分配new []

ZeroMemory用0填充内存块,它不进行任何内存分配。

另外作为旁注,由于您正在处理wchar_t数组,为什么不使用std::wstring

编辑以演示

string getWinTitle(HWND hwnd){
    const int MAX_LENGTH = 1000;
    wchar_t title[MAX_LENGTH];
    ZeroMemory(title, MAX_LENGTH);
    GetWindowText(hwnd, (LPWSTR)title, MAX_LENGTH);
    char* buffer = new char[MAX_LENGTH];
    wcstombs(buffer, title, MAX_LENGTH);
    string res = buffer;

    delete [] buffer; // You must do this, otherwise this is a memory leak if buffer is never deleted

    return res; // res's data is copied from buffer, it is not affected by you doing delete [] buffer
}

避免内存分配

由于您没有使用依赖于运行时值的分配大小,因此可以使用堆栈分配的数组:

string getWinTitle(HWND hwnd){
    const int MAX_LENGTH = 1000;
    wchar_t title[MAX_LENGTH];
    ZeroMemory(title, MAX_LENGTH);
    GetWindowText(hwnd, (LPWSTR)title, MAX_LENGTH);
    //char* buffer = new char[MAX_LENGTH];
    char buffer[MAX_LENGTH]; // this is on the stack
    wcstombs(buffer, title, MAX_LENGTH);
    string res = buffer;
    return res;
} // buffer is automatically cleaned up