The following statements are derived from official Microsoft documentation and are essential for developing safe, correct C programs on Windows.
“New applications should use heap functions, unless the documentation explicitly states that a global function is required.”
This means:
HeapAlloc / HeapFree for buffer management (e.g., in ReadClipboardText).GlobalAlloc / GlobalLock only when the documentation explicitly requires it.| Statement | Meaning |
|---|---|
| Higher Overhead | GlobalAlloc and GlobalLock are system-level functions with higher system overhead and are not optimized for all use cases. |
| Fewer Features | Global functions offer fewer features and are less suitable for modern C applications. |
| New applications → Heap functions | Use HeapAlloc / HeapFree for buffer management – this is the recommended approach. |
Important correction: The function GetClipboardData(CF_TEXT) returns a HANDLE – not an HGLOBAL!
Official documentation makes no statement about the type of handle returned:
“The GetClipboardData function returns a handle to the data in the clipboard.” → This is a generic handle (e.g., for windows, files, processes). → There is no guarantee that it is an HGLOBAL.
GetClipboardData(CF_TEXT) always returns an HGLOBAL.” → This is incorrect and dangerous – leads to crashes when applied to invalid handles.
GlobalLockThe only safe method to read the clipboard is to attempt GlobalLock and check its return value.
If GlobalLock(hData) returns NULL → the handle is invalid or not suitable for GlobalLock → error.
char* ReadClipboardText() {
HANDLE hData = GetClipboardData(CF_TEXT);
if (!hData) {
return NULL;
}
void* p = GlobalLock(hData);
if (!p) {
return NULL;
}
char* text = (char*)p;
DWORD len = strlen(text);
if (len == 0) {
GlobalUnlock(hData);
return NULL;
}
HANDLE hHeap = GetProcessHeap();
void* pBuf = HeapAlloc(hHeap, 0, len + 1);
if (!pBuf) {
GlobalUnlock(hData);
return NULL;
}
char* buf = (char*)pBuf;
memcpy(buf, text, len + 1);
GlobalUnlock(hData);
return buf;
}
Although new applications should use heap functions, GlobalLock is required to read the clipboard – and Microsoft documentation explicitly supports this case.
Why?
GetClipboardData(CF_TEXT) returns a HANDLE – not an HGLOBAL.GlobalLock for NULL.HeapAlloc / HeapFree is the correct and recommended method for buffer management.GetClipboardData(CF_TEXT) returns a HANDLE – not automatically an HGLOBAL. There is no guarantee it is a valid global memory handle. The only safe method is to attempt GlobalLock and check for NULL – if it fails, the handle is invalid or not suitable for GlobalLock.”