tags:

views:

813

answers:

6
+1  Q: 

GDI Leak Problem

Hi all,

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

A: 

(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.

geofftnz
+3  A: 

Make sure that you call ReleaseDC not DeleteDC on handles returned from GetDC.

Matt Davison
+3  A: 

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.)

Ismael
A: 

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.

1800 INFORMATION
A: 

Read the Petzold. GetDC() is really the base.

A: 

You should not be deleting hOldObj on the last line

DeleteObject (hOldObj);

Rene Pilon