What happens if I call GlobalLock () and then not call GlobalUnlock ()?

In Win32, to paste data into the clipboard, I need to call GlobalAlloc() , then GlobalLock() to get the pointer, then copy the data, then call GlobalUnlock() and SetClipboardData() .

If the code is in C ++, an exception may be GlobalLock() between calls to GlobalLock() and GlobalUnlock() , and if I do not take care of this, GlobalUnlock() will not be called.

This is problem? What exactly happens if I call GlobalLock() and for some reason miss the pairing call of GlobalUnlock() ?

+6
memory-management windows visual-c ++ winapi
source share
2 answers

The question is not only whether or not you call GlobalUnlock() . You must call GlobalUnlock() and GlobalFree() . Both must be called in order to free allocated memory:

 HGLOBAL hdl = NULL; void *ptr = NULL try { hdl = GlobalAlloc(); ptr = GlobalLock(hdl); // etc... GlobalUnlock(hdl); ptr = NULL; SetClipboardData(..., hdl ); } catch (...) { if(ptr) GlobalUnlock(hdl); if(hdl) GlobalFree(hdl); throw; } 

Leakage will be widespread. When you exit the Windows application, all allocated private memory is automatically released

+9
source share

More than you really wanted to know about GlobalLock() , courtesy of Raymond Chen:

I mark this community wiki because I really don't know if these articles will answer your question. But they are probably worth going through, at least for pain relief.

But one way to solve your problem with GlobalUnlock () before the exceptions is to use the RAII class to manage calls to GlobalLock() / GlobalUnlock() .

+9
source share

All Articles