Holy cow, I wrote a book!
This rule of real life applies to code as well.
If something doesn't belong to you, then you can't give it away.
For example, functions like
take ownership of the item that you pass it.
In SetClipboardData's case, the memory block you pass
as the hMem parameter becomes the property of the clipboard.
For SetWindowRgn it's the hRgn that becomes
the property of the window manager.
In both cases, you are giving control of the item to another component,
but in order to do that legitimately, it must be yours to give away.
This statement may be obvious, but it's surprising how many people fail
to grasp its consequences. For example, you can't do this:
// error checkin removed to improve readability
// Code in italics is wrong
Once you call SetClipboardData the first time,
the memory now belongs to the clipboard;
it's not yours again.
When you call SetClipboardData a second time,
you're giving it away again,
but the second time, it's not your memory any more.
In other words:
After the first call to SetClipboardData,
the memory belongs to the clipboard.
The second call is trying to give away something that you no longer own.
It reminds me of a news story I read some time ago.
In the United States,
the winner of a major lottery often gets a choice between a
series of payments over several years
or a lump sum.
Somebody won the lottery and agreed to sell the annuity to a company
in exchange for a lump sum.
(Presumably, this company offered a lump sum larger than the one
offered by the lottery.)
And then when the lottery asked whether to disburse the winnings
in the form of an annuity or a lump sum,
the winner opted for the lump sum.
Dude, you can't take the lump sum.
You already sold the revenue stream to that other company.
That's not your money any more.