0

I tried to make a basic text drawing class using SDL and TTF but I got this huge memory leak.. even when I freed the surface :/

this is the textloader.cpp

void TextLoader::drawStringWithShadow(string str,SDL_Rect rct,SDL_Color clr,SDL_Surface *screen)
{
    SDL_Color black = {0,0,0};
    text = TTF_RenderText_Solid(font,str.c_str(),black);
    rct.x++;
    rct.y++;
    SDL_BlitSurface(text,NULL,screen,&rct);
    rct.x--;
    rct.y--;
    text = TTF_RenderText_Solid(font,str.c_str(),clr);
    SDL_BlitSurface(text,NULL,screen,&rct);
    SDL_FreeSurface(text);
}

and the text loader.h

    #pragma once
#include"includes.h"
class TextLoader
{
public:
    TextLoader(const char *Font,int Size);
    ~TextLoader(void);
    void drawString(string str,SDL_Rect rct,SDL_Color clr,SDL_Surface *screen);
    void drawStringWithShadow(string str,SDL_Rect rct,SDL_Color clr,SDL_Surface *screen);
private:
    SDL_Surface *text;
    TTF_Font *font;
};

I am calling this from my main loop

djf
  • 6,592
  • 6
  • 44
  • 62
Daniel Rozen
  • 39
  • 1
  • 5
  • Can you pinpoint the leak using valgrind or similar? It should give you a lot more information than just the fact that you have a leak. Debugging symbols might be needed though. – onitake Jul 08 '13 at 16:26
  • I am running Win8. valgrind support linux/unix.. can you recommend me another program? – Daniel Rozen Jul 08 '13 at 16:45
  • Some suggestions can be found [here](http://stackoverflow.com/questions/413477/is-there-a-good-valgrind-substitute-for-windows). – onitake Jul 08 '13 at 17:53

1 Answers1

3

You are calling TTF_RenderText_Solid() twice, yet you free the surface text created with it only once. On your second call:

 text = TTF_RenderText_Solid(font,str.c_str(),clr);

you overwrite the pointer that points to the previous surface creating a memory leak. You do SDL_FreeSurface() the second surface but not the first one.

Note: TTF_RenderText_Solid returns pointer to completely a new surface.

emartel
  • 7,712
  • 1
  • 30
  • 58
  • I tried to free the surface after the: SDL_BlitSurface(text,NULL,screen,&rct); but it is not working wich surface do I need to free? – Daniel Rozen Jul 08 '13 at 17:04