Question

I wrote this piece of code to print a bitmap to my dialog box in an MFC program (C++ in Visual Studio 2010):

//Loop start
{
    //...
    //some prep stuff
    //...

    HBITMAP hBmp = myObv->GetBMP();
    CBitmap bmp;
    bmp.Attach(hBmp);
    CClientDC dc(this);
    CDC bmDC;
    bmDC.CreateCompatibleDC(&dc);
    CBitmap *pOldbmp = bmDC.SelectObject(&bmp);
    BITMAP  bi;
    bmp.GetBitmap(&bi);
    dc.BitBlt(384,26,bi.bmWidth/3,bi.bmHeight,&bmDC,0,0,SRCCOPY);
    bmDC.SelectObject(pOldbmp);

}

This works fine except that as I continuously run the program and more bitmaps get drawn, the program very rapidly (linerally) begins to chew away at my available memory:

memory

Obviously the rapid drop is me closing the program.

But when I try to delete some of the objects to try to stop the memory leak, my program crashes.

Ex: If I do

    delete hBmp;

I get the error:

error

or if I delete pOldbmp, I get the error:

error

If I declare these objects outside the loop and just keep reusing them, I get fatal abort errors:

fatal

What's the deal??

Why can't I delete these objects?

Was it helpful?

Solution

Use DeleteObject(hBmp) instead.

This is happening because you're attempting to delete hBmp while still having selected it using SelectObject().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top