tags:

views:

50

answers:

2

Basically, on surfaces that are going to exist right until the program terminates, do I need to run SDL_FreeSurface() for each of them, or would SDL_Quit() take care of all this for me?

I ask mainly because the pointers to a number of my surfaces are class members, and therefore I would need to keep track of each class instance (in a global array or something) if I wanted to run SDL_FreeSurface() on each of their respective surfaces. If SDL_Quit() will do it all in one fell swoop for me, I'd much rather go with that :D

+1  A: 

It's been a while since I used SDL, but I'm pretty sure SDL_Quit just cleans up the screen surface (the main screen buffer that you set up at the beginning). You have to free the other surfaces you create manually or you get leaks. Of course, since they're already class members, one way to do that easily would be to just free them up in the class destructor.

Gemini14
Yeah, it's not difficult to free the surface in the destructor, it would just mean keeping track of each instance of the class, since most of the class instances stay around right until the program quits. Thanks!
Lewis
No problem, don't forget to mark answer as accepted ;)
Gemini14
Come to think of it, everything goes out of scope after `main()` is done, so all the destructors would be called upon exit anyways. So no need to keep track of each instance! Correct me if I'm wrong, of course.
Lewis
Yup, you're correct--unless the containing class itself is dynamically allocated (in which case you have to delete them, of course), everything will be auto-released when the object goes out of scope, as you mentioned.
Gemini14
+1  A: 

It is best practise to clear all your surfaces that you know you are using with SDL_FreeSurface().

Similarly, if you create an array of pointers that all call malloc and therefore take up heap space, exiting the program will not clear up all the used space on every system.

int **memspots[1024];
for (i = 0; i < 1024; i++) {
  memspots[i] = malloc(1 * sizeof(int *)); // 1024 pointers to ints stored in heap memory
}

At the end of your application, you would definitely want to call free in a similar fashion.

for (i = 0; i < 1024; i++) {
  free(memspots[i]);
}

It is only best practise to free any memory used any time you can whenever possible, whether at run time and of course at exit.

My GL texture function for SDL temporarily uses an SDL_Surface to gather some image data (taken from SDL_image) and has this at the end:

  if (surface != NULL) // Will be NULL if everything failed and SOMEHOW managed to get here
    SDL_FreeSurface();

  return;