views:

167

answers:

2

In Win32 in order to paste data into the clipboard I have to call GlobalAlloc(), then GlobalLock() to obtain a pointer, then copy data, then call GlobalUnlock() and SetClipboardData().

If the code is in C++ an exception might be thrown between calls to GlobalLock() and GlobalUnlock() and if I don't take care of this GlobalUnlock() will not be called.

It this a problem? What exactly happens if I call GlobalLock() and for whatever reason skip a pairing GlobalUnlock() call?

+2  A: 

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

I'm marking this community wiki because I actually don't know if these articles answer your question. But they're probably worth wading through, at least for a skim.

But one way to handle your problem of dealing with the GlobalUnlock() in the face of exceptions is to use an RAII class to manage the GlobalLock()/GlobalUnlock() calls.

Michael Burr
+3  A: 

The Question is not only about if or if not you call GlobalUnlock(). You must call GlobalUnlock() and GlobalFree(). Both must be called in order to release the memory you allocated:

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;
  }

The leak would be application wide. When you exit a windows application, all allocated private memory is released automatically

RED SOFT ADAIR
Nope, GlobalFree() should not be called if the data is pasted to the clipboard - ownership is passed to the clipborad and it will release memory once later.
sharptooth
Yes you are right, if the call to SetClipboardData has been made successfully. But otherwise, you must call both. Post modified accordingly.
RED SOFT ADAIR