1
votes

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. 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:

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. Also in real code there are nullptr-checks. Just keeping it clean here to reduce amount of guard-clause code.

1
what is rawClipboardData? it doesn't appear to be anything standard. - xaxxon
Seems likely that the problem is coming from CString have you stepped into to it to see where any dynamic allocation is happening? - George
@xaxxon rawClipboardData is a CString variable that I simply create on the stack (sending in the "ch" char pointer into its constructor) to create a CString from a char* - 10100111001
@10100111001 Yes but what is CString? Something will be either new'd or malloc'd inside, it doesn't matter that the CString obj itself is stack allocated. Unless of course the leak isn't actually coming from CString rawClipboardData(ch); - George
We need a minimal reproducible example. As it stands, your CString object is never used anywhere. The code you posted doesn't leak memory. If there really is a leak (which may not actually be the case), it is in the code we cannot see. - IInspectable

1 Answers

-2
votes

GlobalLock(hglb) should be a LPTSTR so I would assume that the leak is caused by the cast to char*. For Unicode platforms, TCHAR is defined as synonymous with the WCHAR type.

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