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;
}
开发者_JAVA百科
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
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
精彩评论