我写了这个代码:
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分配的内存吗? 我需要明确释放分配给缓冲区的内存吗?
谢谢
你需要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