Evan Carslake
Evan Carslake

Reputation: 2359

C++ Win32 Gdiplus program crash trying to delete Gdiplus::Bitmap

Basically, I am trying to find out if a Gdiplus::Bitmap* is not NULL (or 0). If so delete it, and then create a "new Gdiplus::Bitmap()" in place. I am trying to do this to prevent any future memory leak.

I've tried quite a few things, if I create the bitmap and then call delete, it works fine (minus the null check.)

// private
Gdiplus::Bitmap* last_frame_bmp;

// public
foo::foo() {
    if (last_frame_bmp != NULL) { delete last_frame_bmp; }
    last_frame_bmp = new Gdiplus::Bitmap(100, 100, PixelFormat32bppPARGB);
}

By crash, I mean, the program hangs and doesn't start.

Any ideas?

Upvotes: 0

Views: 723

Answers (3)

Evan Carslake
Evan Carslake

Reputation: 2359

The solution was to set Gdiplus::last_frame_bmp = NULL in the constructor of the class. It now works as intended.

Upvotes: 1

c-smile
c-smile

Reputation: 27470

You are using non-initialized variable.

Change it to

Gdiplus::Bitmap* last_frame_bmp = nullptr;

and it will work.

BTW: Do you call GdiplusStartup to initialize GDI+ ? You have to.

Upvotes: 1

Alan Stokes
Alan Stokes

Reputation: 18972

Well, your test is the wrong way round - you're only deleting if it's null. In any case it is entirely safe to delete a null pointer; it has no effect, so you'd be much better off without the condition at all.

But no good C++ code ever does an explicit delete anyway; we have smart pointers to do that for us.

Your crash is because you corrupted memory somewhere else - too much explicit new and delete I would think.

Upvotes: 2

Related Questions