你需要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