Reputation: 39
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
Upvotes: 0
Views: 2481
Reputation:
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.
Upvotes: 3