Question

I've nailed the culprit of my memory leak down to the rendering of text, and don't understand why every 2 seconds the amount of physical memory the program is using goes up by about 0.02 GB. Could you help?

#include "Text.h"


CText::CText()
{
    TTF_Init();
}


CText::~CText()
{
    free(mfont);
        free(message);
    free(tex);
}

void CText::Draw(std::string font, int size, std::string m_text, SDL_Renderer* renderer, int x, int y, SDL_Color color)
{
    int w = 0;
    int h = 0;

    mfont = TTF_OpenFont(("res/" + font + ".ttf").c_str(), size);
    message = TTF_RenderText_Solid(mfont, m_text.c_str(), color);
    tex = SDL_CreateTextureFromSurface(renderer, message);
    SDL_QueryTexture(tex, NULL, NULL, &w, &h);
    textRect.x = x;
    textRect.y = y;
    textRect.w = w;
    textRect.h = h;

    SDL_RenderCopy(renderer, tex, NULL, &textRect);

    TTF_CloseFont(mfont);
}

Thanks..

Was it helpful?

Solution

Every time you call Draw, you create a new texture in tex without freeing the previous one.

Your destructor is also wrong... free is only for memory allocated with malloc (or calloc or realloc). As you are not using malloc anywhere, you really have no business using free.

  • I don't think mfont is valid at this point (you're freeing it in Draw().
  • tex should be freed with SDL_DestroyTexture.
  • message also should be freed by SDL_FreeSurface.

I think the short answer is that you just need to read, understand, and follow the documentation for the APIs you are trying to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top