简体   繁体   中英

Can't find the memory leak in this code

I've been looking for over 2 hours and it turns out my memory leak is coming from this section, only I am unable to determine what is causing the leak. BTW, I am using Allegro5, but made some wrappers.

void WidgetLabel::updateBitmap( Display* display )
{

    Size textSize = getTextSize( _font, _text.c_str() );

    _bitmap = createBitmap( textSize.getWidth(), textSize.getHeight(), display );

    startDrawingToBitmap( _bitmap );
        drawText( _font, _color, Point(0,0), _text.c_str() );
    stopDrawingToBitmap( _bitmap, display );

}

Edit: I thought I might need to delete the _bitmap to free the space before creating a new one, but the application keeps crashing when doing so. I am guessing it is because of how Allegro manages memory. With Allegro, you must do:

al_destroy_bitmap( ALLEGRO_BITMAP* bitmap );

Well you need to delete things when you create them on the heap. It sounds like you need to delete _bitmap, but only if you've used it before; it would crash if you hadn't set it to something before you tried to delete it.

Assuming that createbitmap allocates memory, are you overwriting _bitmap always, when you call updateBitmap() ? (Is there any statement you are missing to manage _bitmap ?)

It might crash, if _bitmap is not initialized and you are trying to free it. You can initialize _bitmap in constructor as 0 and then check for NULL before freeing it. ie

if(_bitmap != 0)
  delete or free (_bitmap); 

If I may be completely honest, createBitmap() is not the counterpart of al_destroy_bitmap() .

al_create_bitmap() is.

Your createBitmap() may have come from somewhere else. Check it's signature.

A few thoughts:

  1. How do you know that you have a memory leak? What is your indication of this? Sometimes the task manager or top are inaccurate, because while the memory has been freed, it may not have been re-allocated by the OS yet.

  2. If you are calling this function repeatedly, it may be that _bitmap is being allocated (using createBitmap) but its memory is not being free()'d. Is there also a "DestroyBitmap" or "FreeBitmap" function?

If _bitmap already contains another image when you createBitmap, you will lose that pointer and leak memory. Additionally, as you mentioned, you need to destroy the bitmap as well.

It may be worth your time to find out why it's crashing if you do free the bitmap, are you reusing the pointer to the freed bitmap again unintentionally?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM