   [SDL] Memory leak question
  Hi,I had a small problem with a memory leak. I've fixed it but I'm not really understanding my solution. Here is some psudo code to discribe the original problem. while {...  Surface1 = TTF_RenderText_Solid(.......);  Surface1 = SDL_DisplayFormat(Surface1);  SDL_FreeSurface(Surface1);...}I used this same style for all my images and it seemed to work with no problems. With the above code I get a memory leak. The solution I'm using now is to use a Temp surface.while {...  Temp = TTF_RenderText_Solid(.......);  Surface1 = SDL_DisplayFormat(Temp);  SDL_FreeSurface(Surface1);  SDL_FreeSurface(Temp);...}That seems to have solved the problem. My real question here is why? I don't understand why it's nessisary in this case to assign it to a temp surface first, when all my images did not need that treatment. Also....while {...  Temp = TTF_RenderText_Solid(.......);  Surface1 = SDL_DisplayFormat(Temp);  Temp = TTF_RenderText_Solid(.......);  Surface2 = SDL_DisplayFormat(Temp);  SDL_FreeSurface(Surface1);  SDL_FreeSurface(Surface2);  SDL_FreeSurface(Temp);...}This scenario gives me a memory leak as well, unless I free the temp surface in between the two assignments.If anyone could clarify this it would be a big help. I might be able to sleep at night. [disturbed]   
  SDL_DisplayFormat() makes a new surface with the screen's format and blits the image you passed in to it.  So now you have to free the image you passed in as well as the image it gave you (it doesn't free anything, you have to).   ;  The real issue here is that SDL_DisplayFormat creates a deep copy of the surface you passed.In you original code:Surface1 = TTF_RenderText_Solid(.......);Surface1 = SDL_DisplayFormat(Surface1);SDL_FreeSurface(Surface1);Surface1 points to a surface that is created by TTF_RenderText_Solid. Then when SDL_DisplayFormat is called, Surface1 points to a new surface created by the call. The pointer top the original surface is lost. Your second snippet solves this problem by freeing both.Your last snippet:Temp = TTF_RenderText_Solid(.......);Surface1 = SDL_DisplayFormat(Temp);Temp = TTF_RenderText_Solid(.......);Surface2 = SDL_DisplayFormat(Temp);SDL_FreeSurface(Surface1);SDL_FreeSurface(Surface2);SDL_FreeSurface(Temp);Creates a memory leak because the surface Temp points to after the first call is never freed. When the next call to TTF_RenderText_Solid is made, you lose the original pointer.I would suggest using a utility function for this:SDL_Surface* RenderText(......){    SDL_Surface* temp = TTF_RenderText_Solid(.......);    SDL_Surface* text = SDL_DisplayFormat(Temp);    SDL_FreeSurface(temp);    return text;}Just be sure that you eventually call SDL_FreeSurface on the surfaces returned by this function.Hope that made sense.   ;  Oh. Well that makes sense now. Thanks :) A utility function is a great idea. Now if I could only get it to work right... 