I am using SDL and this function cause my program to use all of my memory

134 views Asked by At

I am a beginner to C++ and this function cause the memory of my program to continuously raise.

It's called in a while loop and it never stop.

void text_box()
{
    SDL_Surface *MESSAGE1 = TTF_RenderText_Solid( font,  "Ligne #1" , noir );                     
    SDL_Surface *MESSAGE2 = TTF_RenderText_Solid( font,  "Ligne #2" , noir );
    SDL_Surface *MESSAGE3 = TTF_RenderText_Solid( font,  "Ligne #3" , noir );
    SDL_Surface *MESSAGE4 = TTF_RenderText_Solid( font,  "Ligne #4" , noir );
    SDL_Surface *MESSAGE5 = TTF_RenderText_Solid( font,  "Ligne #5" , noir );
    SDL_Surface *MESSAGE6 = TTF_RenderText_Solid( font,  "Ligne #6" , noir );
    SDL_Surface *MESSAGE7 = TTF_RenderText_Solid( font,  "Ligne #7" , noir );
    SDL_Surface *MESSAGE8 = TTF_RenderText_Solid( font,  "Ligne #8" , noir );
    SDL_Surface *MESSAGE9 = TTF_RenderText_Solid( font,  "Ligne #9" , noir );
    SDL_Surface *MESSAGE10 = TTF_RenderText_Solid( font,  "Ligne #10" , noir );
    apply_surface( 0, 403, MESSAGE1, SCREEN );
    apply_surface( 0, 412, MESSAGE2, SCREEN );
    apply_surface( 0, 421, MESSAGE3, SCREEN );
    apply_surface( 0, 429, MESSAGE4, SCREEN );
    apply_surface( 0, 438, MESSAGE5, SCREEN );
    apply_surface( 0, 447, MESSAGE6, SCREEN );
    apply_surface( 0, 456, MESSAGE7, SCREEN );
    apply_surface( 0, 465, MESSAGE8, SCREEN );
    apply_surface( 0, 474, MESSAGE9, SCREEN );
    apply_surface( 0, 483, MESSAGE10, SCREEN );
}

It raise in a linear way until there is no more memory left.

1

There are 1 answers

4
Joe Z On

TTF_RenderText_Solid returns a pointer to a new SDL_Surface.

You need to free this surface when you're done with it.

In this particular case, since your text never changes, and I'm guessing font and noir are fixed, you could initialize MESSAGE1 through MESSAGE10 once, and reuse them, as suggested by Bartlomiej Lewandowski below. Then you only need to free the surfaces if you reach a part of your program where they're no longer needed for display.