Josh D Josh D - 3 months ago 31
C++ Question

Does loading an image in the same surface free the old image?

I'm new to SDL and, in this part of my program, I would like to be able to change the image of an existing surface. My question is, will this automatically unload the previous image or will I have to use SDL_FreeSurface() and then reload the surface altogether? I don't want to end up with a large amount of images loaded that don't need to be loaded. Visual explanation:

string path = "Image.png";
SDL_Surface* loadedSurface = IMG_Load((path.c_str());

If I use loadedSurface again with a different image, will the original one be unloaded?

path = "NewImage.png";
loadedSurface = IMG_Load(path.c_str());

Or will I have to do something like this every time I load a new image:

path = "NewImage.png";
SDL_Surface* loadedSurface = IMG_Load(path.c_str());

This may be alright, I'm just not sure if creating a new surface every loop will be more intensive than another, easier way. Thank you!


You need to call SDL_FreeSurface before loading a new surface and overwriting the old pointer.

Think about it: at the point you call IMG_Load the second time, SDL is just loading the image, and doesn't know what you're going to do with the returned pointer. So it can't free any of the already loaded surfaces. You have to do that yourself.