I am using SDL_TTF to draw text and have a memory leak that I have narrowed down to the above function, specifically this line: text_surface = TTF_RenderText_Blended(temp_font, text.get_string().c_str(), text_colour);
After using the surface in opengl I am calling SDL_FreeSurface before the function above is run again however it is still leaking.
If I disable the opengl function that draws the surface to the screen it still leaks, however if I comment out the TTF_RenderText_Blended line it doesn't leak.
class Renderer{
public:
Renderer();
bool is_font_cached(std::string font_name, int font_size);
void render(std::vector<Shape> shapes_to_render);
void resize();
void rasterize(int width, int height);
void cleanup();
void update_window();
void draw_surface();
void cache_font(std::string font_name, int font_size);
std::vector<float> cartesian_to_opengl(std::vector<float> cartesian_coordinates);
std::vector<int> get_window_dimensions();
Font get_font(std::string font_name, int font_size);
void text_to_sdl_surface(Text text, Colour colour);
void draw_sdl_surface(float xpos, float ypos);
int get_width_of_text(std::string text);
SDL_Surface * &get_text_surface();
private:
SDL_Window * window;
SDL_GLContext glContext;
std::vector<Font> font_cache;
SDL_Surface * text_surface;
};
In the render function I call both text_to_sdl_surface and draw_sdl_surface, after that I use SDL_FreeSurface inside of the render function to free the surface:
If the program is left to run it crashes. If i have task manager open when it runs I can watch it's memory use continually rise proportional to the number of calls to text_to_sdl_surface in each cycle of the main loop.
If i comment out the call to draw_sdl_surface it still leaks. :/
Thanks for the help! :)
It looks like you never free the TTF_Font. You have a class called Font so you probably should free the TTF_Font in the Font destructor. If you do that you will also have to make sure to keep the Font object alive for as long as you use the TTF_Font.
1 2
Font font = get_font(text.get_fontname(), text.get_fontsize()).get_font();
text_surface = TTF_RenderText_Blended(font.get_font(), text.get_string().c_str(), text_colour);
For the above to work you will also have to implement proper copy/move semantics for the Font class.