[SDL] dynamic memory allocation and SDL_Surfaces

Christer Sandberg christer.sandberg at mdh.se
Wed Sep 5 23:54:18 PDT 2007


Wednesday 05 September 2007 wrote Chris Dickinson:
> I have a question about freeing pointers to surfaces - I'm trying to figure
> out whether my program might have a memory leak.  In one function, I use
> malloc () to create a pointer to an array of SDL_Surfaces. I then load
> various images onto the surfaces and pass a pointer to the array to a
> second function.  In the second function, I use malloc() to create a second
> array of pointers to SDL_Surfaces, and I use this array to access the
> surfaces passed to the function (I know that on the surface this sounds
> odd, but within the program there is a good reason for doing this).  After
> the called function returns, I free each of the surfaces in the array
> [i.e., for (i=0; i<nSurfaces; i++) SDL_FreeSurface(surface1[i])] and then
> free the pointer [free(surface1)].  If I do this, but don't attempt to free
> the pointers created in the second function, the program works as it
> should, and I don't see any obvious evidence of memory leaks.  If in the
> function that is called I try to free the pointers to the individual
> surfaces that were allocated with the call to malloc() [i.e., for (i=0;
> i<nSurfaces; i++) SDL_FreeSurface(surface2[i])], I get a seg fault (which
> is expected).  If, however, I simply free the pointer [i.e., free
> (surface2)], I don't get a seg fault.  My question is whether I need to
> free the pointer of SDL_Surfaces allocated in the called function or not
> (and if not freeing it will result in a memory leak).  I know that if I
> were passing a pointer to a single surface and then accessing it with
> another pointer, freeing both would cause a seg fault (only the pointer to
> the original surface should be freed - the one that was passed).  If anyone
> has any thoughts, they would be greatly appreciated.  If it matters, I'm
> coding in C (MS C++ 6.0 Professional).  Thanks.
For each malloc you should have exactely one free to avoid memory leaks. So, 
yes, you should free(surface2).
-- 
Christer


More information about the SDL mailing list