Search code examples
c++sdl

SDL2 text rendering memory usage grows linearly


I'm using SDL2 to draw text, but the memory usage in Visual Studio grows linearly until the program crashes. I have been told to disable adress sanitizer in the project properties, but I'm not enabling it. Does anyone knows how to address this issue ?

This is the code that I am using:

class Textura {
    public:
        Textura() {
            textur = NULL;
            largura = 0;
            altura = 0;
        };
    virtual ~Textura() {};
    protected:
    SDL_Texture* textur;
    int largura, altura;
};

class Texto : public Textura {
    public:
    Texto() {};
    ~Texto() {};
    void rendTex(int x, int y, std::string textoo, SDL_Color cor, TTF_Font* fonte) {        
        SDL_DestroyTexture(textur);
        SDL_Surface* superficie = TTF_RenderText_Solid(fonte, textoo.c_str(), cor);
        textur = SDL_CreateTextureFromSurface(Janela::rende, superficie);
        largura = superficie->w;
        altura = superficie->h;
        SDL_FreeSurface(superficie);
        SDL_Rect quadrado = { x, y, largura, altura };
        SDL_RenderCopy(Janela::rende, textur, nullptr, &quadrado);
    }
};


int main(int argc, char* args[]) {
    
    bool fim = false;
    Texto tex1;

    while (!fim) {
        while (SDL_PollEvent(&eve)) {}
        tex1.rendTex(50,50,"This is a text",{255,255,255,0},TTF_OpenFont("arial.ttf", 22));
        
    janela.clear();
    }
    return 0;
}

Solution

  • The solution here is to divide the "rendTex" method in two parts. This is the first part, that must be placed out of the rendering segment of the loop:

    void Texto::CarrTextura(std::string textoo, TTF_Font* fonte, SDL_Color cor) {
        SDL_DestroyTexture(textur);
        SDL_Surface* superficie = TTF_RenderText_Solid(fonte, textoo.c_str(), cor);
        textur = SDL_CreateTextureFromSurface(Janela::rende, superficie);       
        largura = superficie->w;
        altura = superficie->h;
        SDL_FreeSurface(superficie);
    }
    

    This the second part, that is placed in the rendering segment of the loop:

    void Texto::rendTex(int x, int y) {
        SDL_Rect quadrado = { x, y, largura, altura };
        SDL_RenderCopy(Janela::rende, textur, nullptr, &quadrado);
    }