HBITMAP memory leak

7.1k Views Asked by At

No matter how hard I looked and whatever I tried, I couldn't find why this code is leaking. Actually, I'm not sure about the leak but the number of GDI objects increases everytime I use this piece of code.

HBITMAP hBmp;
hBmp = CreateDIBitmap(dc, &stBmpIH, CBM_INIT, m_pBitmapData, m_pBitmapInfo, DIB_RGB_COLORS) ;

Bitmap  *pBMP = NULL;
HPALETTE hPal = NULL;
Color col = 0;

pBMP = Bitmap::FromHBITMAP(hBmp, hPal);

if (m_bFlip)
{
    pBMP->RotateFlip( Rotate90FlipXY );
    pBMP->GetHBITMAP(col,&hBmp);
    m_bFlip = FALSE;
}
else
{
    pBMP->RotateFlip( RotateNoneFlipX );
    pBMP->GetHBITMAP(col,&hBmp);
}

delete pBMP;

I've checked the GDI objects with a tool, and what I found is the HBITMAP hBmp is the one that is leaking. How should I remove it?

DeleteObject is NOT working.

Thanks

3

There are 3 best solutions below

1
Hans Passant On BEST ANSWER

DeleteObject is NOT working.

Let's assume that it is actually in your code even though the snippet doesn't show it. Then the next explanation is this statement:

 pBMP->GetHBITMAP(col,&hBmp);

Which overwrites the value for hBmp, preventing you from releasing it properly. Fix:

 HBITMAP prev = hBmp;
 Status status = pBMP->GetHBITMAP(col,&hBmp);
 if (status == Ok) DeleteObject(prev);

You'll probably need to do some more work on the error handling code.

0
Dabbler On

You need a call to DeleteObjectto match the call to CreateDIBitmap. How exactly is it now working?

0
Mark Ransom On

From the FromHBITMAP documentation:

You are responsible for deleting the GDI bitmap and the GDI palette. However, you should not delete the GDI bitmap or the GDI palette until after the GDI+ Bitmap object is deleted or goes out of scope.

Deleting the Bitmap object is not enough, you need to call DeleteObject on hBmp afterwards.