[英]C++ MFC: Memory Leak When Creating CString From Char*
I am getting a memory leak when I run try to read from Clipboard. 我尝试从剪贴板读取内容时遇到内存泄漏。
Sample code: 样例代码:
void SomeFunction()
{
OpenClipboard(nullptr);
HGLOBAL hglb = GetClipboardData(CF_TEXT);
char* ch = static_cast<char*>(GlobalLock(hglb));
CString rawClipboardData(ch);
GlobalUnlock(hglb);
CloseClipboard();
}
It is the middle row above which causes the memory leak according to Visual Studio. 根据Visual Studio,它是上方的中间行,导致内存泄漏。 This row:
该行:
CString rawClipboardData(ch);
If I do not run it, there is no leak reported. 如果我不运行它,则没有泄漏报告。 But if I do run it I get the following debug output in visual studio output window:
但是,如果我运行它,则会在Visual Studio输出窗口中获得以下调试输出:
Detected memory leaks!
Dumping objects ->
f:\dd\vctools\vc7libs\ship\atlmfc\src\strcore.cpp(158) : {75645} normal block at 0x00000000072C89A0, 52 bytes long.
Data: <`x > 60 78 F7 D3 FE 07 00 00 0D 00 00 00 0D 00 00 00
Object dump complete.
Any ideas? 有任何想法吗?
UPDATE: Added OpenClipboard(nullptr) in code above. 更新:在上面的代码中添加了OpenClipboard(nullptr)。 Also in real code there are nullptr-checks.
在真实代码中也有nullptr-checks。 Just keeping it clean here to reduce amount of guard-clause code.
只是保持此处干净以减少保护条款的数量。
GlobalLock(hglb) should be a LPTSTR
so I would assume that the leak is caused by the cast to char*
. GlobalLock(hglb)应该是
LPTSTR
所以我认为泄漏是由强制转换为char*
引起的。 For Unicode platforms, TCHAR is defined as synonymous with the WCHAR type. 对于Unicode平台,TCHAR被定义为WCHAR类型的同义词。
you should be able to do something like 你应该能够做类似的事情
CString rawClipboardData = GlobalLock(hglb);
If not then 如果没有
CString rawClipboardData;
LPTSTR lptstr = GlobalLock(hglb);
rawClipboardData = lptstr;
will definitely work 肯定会工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.