mic*_*123 2 c++ memory windows 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;
}
Run Code Online (Sandbox Code Playgroud)
这里有内存泄漏吗?我是否需要释放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
}
Run Code Online (Sandbox Code Playgroud)
避免内存分配
由于您没有使用依赖于运行时值的分配大小,因此可以使用堆栈分配的数组:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1394 次 |
| 最近记录: |