SDL_FreeSurface = seg fault

Hi I was trying out some collision detection and I have a problem. I have 2 objects, and when they collide, I want one of the objects to dissapear. Therefore, when I tested for collision, I called SDL_FreeSurface(itemSurface) when the collision was true. This causes a segmentation fault. Is there some other way to remove objects?

I test for collision using a method called intersects, whichs takes a SDL_Rect as a paramater. It returns true or false. The collision works, its just the segmentation fault I get when i try to freesurface of the item sprite

Hello!

You should be a little cautious with freeing the surface because some objects may share an image.

There are two things that I know of that would cause a seg fault when it comes to freeing memory.

  1. the pointer is NULL or not pointed to memory that was malloced
  2. the free command completes successfully, but then a later command attempts to use that freed pointer.

A fairly orderly way to manage it is to have a resource manager that loads all the images you’ll be using, and when creating an object, it pulls a reference from the resource manager.

Then you can either delete the object, or just set it’s state to inactive/dead/etc so it doesn’t get drawn.

And then during the cleanup phase of exiting, you just free all stored by the resource manager.> Hi I was trying out some collision detection and I have a problem. I have 2 objects, and when they collide, I want one of the objects to dissapear. Therefore, when I tested for collision, I called SDL_FreeSurface(itemSurface) when the collision was true. This causes a segmentation fault. Is there some other way to remove objects?

I test for collision using a method called intersects, whichs takes a SDL_Rect as a paramater. It returns true or false. The collision works, its just the segmentation fault I get when i try to freesurface of the item sprite

Why not just leave the surface in memory until the program ends and then free it at the end, and in the meantime just take it off the screen?