[SDL] dynamic memory allocation and SDL_Surfaces

Chris Dickinson cdickins at udel.edu
Wed Sep 5 13:29:32 PDT 2007


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.

Regards,

Chris Dickinson, PhD
Department of Psychology
University of Delaware



More information about the SDL mailing list