Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I call GlobalLock(), then fail to call GlobalUnlock()?

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?

like image 817
sharptooth Avatar asked Jan 29 '10 08:01

sharptooth


1 Answers

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

like image 124
RED SOFT ADAIR Avatar answered Oct 03 '22 15:10

RED SOFT ADAIR