Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does it lead to memory leak?

I wrote this code:

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;
}

is there a memory leak here? do I need to free memory allocated by ZeroMemory? do I need to explicitly free memory allocated for buffer?

Thank you

like image 635
michaels123 Avatar asked Mar 23 '26 20:03

michaels123


1 Answers

You need to delete [] buffer; since it's new [] allocated.

ZeroMemory fills a memory block with 0s, it doesn't do any memory allocation.

Also as a side note, since you're dealing with wchar_t arrays, why aren't you using std::wstring?

edit to demonstrate

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
}

Avoiding the memory allocation

Since you are not using an allocation size dependent on runtime values, you can use stack-allocated arrays:

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
like image 123
逆さま Avatar answered Mar 25 '26 09:03

逆さま



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!