0

I have a huge memory leak which is making me question my implementation of SDL_TTF as a whole.

Right now I have the following classes

MainMenu
Menu
Options
Button 
Text

The MainMenu and Option classes abstract the menu class and each call their own button class with parameters that build the text class.

So right now my main loop passes the SDL_Renderer (gRenderer) down through a MainMenu->Button->Text path.

When my Text class is initialized it loads the font, sets up the font using TTF_RenderText_Solid with the message that has been passed in by the Button class, and the TTF_SetFontStyle to set the text bold.

I draw using:

void Text::draw(SDL_Renderer* gRenderer)
{   
renderQuad = { getXPosition(), getYPosition() };//, getWidth(), getHeight()};   
mTexture = SDL_CreateTextureFromSurface(gRenderer, message);
SDL_RenderCopyEx(gRenderer, mTexture, NULL, 
                    &renderQuad, NULL, NULL,  SDL_FLIP_NONE);
};

I believe it is bloating on SDL_CreateTextureFromSurface or SDL_RenderCopyEx.

What can I do to amend this memory leak? Am I overlooking something blatant?

Solution:

Discovering/Using Twinklebear's ifnroamtion:

When declaring the object in the header, I declared the texture and set it equal to NULL By: SDL_Texture* mTexture = NULL;

Then, inside of the draw function I check if the texture is set to NULL or not:

void Text::draw(SDL_Renderer* gRenderer)
{    

renderQuad = { getXPosition(), getYPosition(), message->w, message->h };

if (mTexture == NULL)
{
    mTexture = SDL_CreateTextureFromSurface(gRenderer, message);
}

SDL_RenderCopy(gRenderer, mTexture, NULL, &renderQuad);
};

What I would like to do is throw a boolean variable on the class to state if the texture needs updated or not, and reset the texture.

Elias
  • 2,602
  • 5
  • 28
  • 57

1 Answers1

0

If you're calling the draw function each frame you're creating lots of textures but not freeing them, causing your memory leak.

mTexture = SDL_CreateTextureFromSurface(gRenderer, message);

creates a new texture of the message which you need to free later on with SDL_DestroyTexture, if you don't free this texture you'll leak the memory and if you leak a texture every frame it'll start to add up really quick.

To fix this you shouldn't reload the surface into a texture unless you're changing the message displayed since there's no need to re-create the same texture each frame (it's also pretty slow to do this each frame).

Twinklebear
  • 361
  • 2
  • 4
  • Yeah, it was exactly as you say. I actually made a mistake because of my inexperience with C++ that I will add on to your answer, if you don't mind? – Elias Jun 02 '14 at 01:06
  • 1
    Sure that's fine. You might also want to pick up a book on C++, memory management is pretty important for games/C++ code in general. There's a good list over [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Twinklebear Jun 02 '14 at 01:24