Search code examples
winapimemory-leaksgdi

What is, and why do I have to restore bitmap hdc or memory dc to the default state when cleaning up?


When I was looking at BitBlt() examples, I noticed almost all of them were saving the default state of the hdc for bitmaps and then restoring the hdc to the default state using SelectObject() at clean up. Including the source code for Nethack for windows.

Except one of them which wasn't doing that and just cleaning up hdc and bitmaps like how I was doing. I don't see how restoring the hdc to the default state has got something to do with memory leak. Isn't just deleting the hdc enough? Does the hdc loads data or something when you SelectObject() it to a bitmap that you have to restore it to clean it up?


Solution

  • In addition to what @IInspectable said, you don't HAVE to restore the DC; you only have to "un-select" GDI object that you've allocated from that DC. Otherwise, you can't delete an object that is currently selected into any DC.

    The SelectObject() API conveniently returns to you a previously selected object, so you can just re-select it when you are done with that DC.

    Also, to clarify, those issues cause resource leaks (non memory leak). That can be worse, since the resources have a pretty low limits (like 10,000 handles, IIRC).