1

When using SDL_Surfaces to handle images, I run into the problem that running SDL_FreeSurface(SDL_Surface *) (doc) twice on the same pointer yields a segmentation fault.

I understand why that happens, but I need to know how I can avoid that. I'd like to check the state of the pointer (find out if its pointing to an existing surface) and then Free the surface only if necessary.

How can I do that?

Malabarba
  • 4,473
  • 2
  • 30
  • 49
  • 4
    You can set the pointer to NULL after you delete it first time. But with a good design, deleting twice shouldn't happen in the first place; maybe look up RAII (http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization). – jrok Oct 21 '11 at 14:05
  • @jrok: True, I guess I was kind of looking for the easy way out. Shame on me for being lazy. :-P – Malabarba Oct 21 '11 at 14:25

1 Answers1

4

You write a class that encapsulates an SDL_Surface pointer which frees the surface in it's destructor. Also, make sure you properly implement or disable the copy constructor and the assignment operator. (see The rule of 3)Then, you never work directly with SDL_Surface pointers again.

Here's an example of a wrapper around SDL that I was working on a while ago.

I stopped work once I learned about SFML.

Community
  • 1
  • 1
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • The problem with SDL_Surface pointers is, that you are not supposed to free everyone you get, depending on the function you get it from.. >_> `SDL_SetVideoMode` for example returns a pointer that shouldn't be freed. – Xeo Oct 21 '11 at 14:10
  • @Xeo: Yes, you need to encapsulate that idea too. In the example I linked to, the Window class encapsulates the surface returned by SDL_SetVideoMode, and the Surface class handles all others. Both classes derive from abstract class DrawDestination. – Benjamin Lindley Oct 21 '11 at 14:14
  • Like Xeo said, that's exactly my problem. The reason I'm asking this is exactly the fact that I'm trying to write a class for handling the surfaces. The problem is that some surfaces need to be reloaded during run time, but (of course) I need to free it before reloading. But if it happens to not be loaded yet, I get a segfault. – Malabarba Oct 21 '11 at 14:16
  • 1
    @Bruce: Set the pointer to NULL during construction. Before you free it, check if it's NULL. After you free it, set it to NULL again. For special surfaces(like the one returned by SDL_SetVideoMode), there are two options. You can keep a flag in your class telling you it's special, so don't free it. Or you can use different classes for those surfaces, like I did. – Benjamin Lindley Oct 21 '11 at 14:21
  • @BenjaminLindley: Thanks. And what's your verdict on SFMLK? :-) – Malabarba Oct 21 '11 at 14:24
  • 1
    @Bruce: SFMLK? The San Francisco Martin Luther King Civic Committee? I can't comment on it. Or SFML? I love it. – Benjamin Lindley Oct 21 '11 at 14:26