问题
I noticed using task manager that the following code has a GDI leak in it. The count of GDI object in the process executing this code increases by 1 each time it executes however I can't seem to find the problem.
Any help would be appreciated.
// create new DC based on current
HDC hDC = CreateCompatibleDC(GetDC());
// select a bitmap into the new DC and keep the old one
HGDIOBJ hOldObj = SelectObject (hDC,hBM);
// do somthing here --> 100% no leak here
SomeFunction (hDC);
// select the old object back from whence it came and delete whats returned
DeleteObject (SelectObject (hDC,hOldObj));
// delete the DC
DeleteDC(hDC);
// delete the tmp object
DeleteObject (hOldObj);
RM
回答1:
Copying from the comment, I didn't put it as answer as I can't test it and I was not sure if it was correct, please test it.
In general it is not a good idea to have nested calls ie
HDC hDC1 = GetDC();
HDC hDC2 = CreateCompatibleDC(hDC1);
..
instead of
HDC hDC = CreateCompatibleDC(GetDC());
(BTW in your code the HDC returned by GetDC is not released.)
回答2:
Make sure that you call ReleaseDC
not DeleteDC
on handles returned from GetDC
.
回答3:
I can advise deleaker to find and fix leaks.
回答4:
(I was about to say this when I noticed there was already a comment with the answer - credit goes to xhantt)
I dont think the dc created by GetDC() on the first line is released.
回答5:
I guess this question is already answered. I want to jump in and recommend various smart pointer classes and wrappers that are available for GDI objects.
MFC has the various GDI related objects such as CDC and CMemoryDC and so on. They will perform the correct deletion when they are no longer required.
回答6:
Read the Petzold. GetDC() is really the base.
回答7:
You should not be deleting hOldObj on the last line
DeleteObject (hOldObj);
来源:https://stackoverflow.com/questions/482083/gdi-leak-problem