[Clipboard] Do I need to call GlobalFree when using setClipboardData ?

dhkim 1 Reputation point
2021-10-28T09:49:45.633+00:00

in the code below, When GlobalFree is called, an error occurs in GlobalAlloc when GetClipboardData is called.

MSDN doesn't mention GlobalFree when calling SetClipboardData.

if (OpenClipboardEx(m_hViewer))  
{  
	  
	hglbCopy = GlobalAlloc(GMEM_MOVEABLE,	  
	  
	lptstrCopy = (LPTSTR)GlobalLock(hglbCopy);  
	memcpy(lptstrCopy, &szTest, cch * sizeof(TCHAR));  
	lptstrCopy[cch] = (TCHAR)0;     
	GlobalUnlock(hglbCopy);  
	  
	::SetClipboardData(CF_UNICODETEXT, hglbCopy);  
	CloseClipboard();  
   **GlobalFree(hglbCopy);**  

}

So when GloballAlloc is called, I thought that GlobalFree calls were natural.

Some Internet articles say that GlobalFree should not be called, but I can't see any official information related to MSDN.

If you know anything about this, please reply.

thank you.

My previous question
clipboard-getclipboard-globallock-fail-1.html

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,532 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 40,471 Reputation points
    2021-10-28T09:59:28.587+00:00

    No, do not call GlobalFree after putting data on the clipboard. Think about it this way -- you are transferring ownership of the global memory block from your application to the clipboard. When the clipboard no longer needs the data, it will release the memory by calling GlobalFree itself.

    Official documentation from SetClipboardData function -- "If SetClipboardData succeeds, the system owns the object identified by the hMem parameter. The application may not write to or free the data once ownership has been transferred to the system..."

    0 comments No comments