I have a simple program that tries to render a text on a window with SDL_ttf:
#include <stdio.h>
#include <SDL.h>
#include <SDL_ttf.h>
#include <stdbool.h>
SDL_Renderer* renderer;
TTF_Font* font = NULL;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* win = SDL_CreateWindow("Title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
// Font
if (TTF_Init() < 0)
{
printf("Failed to initialize TTF!\n");
}
font = TTF_OpenFont("arial.ttf", 12);
if (!font)
{
printf("Failed to load font!\n");
}
bool quit = false;
SDL_Event e;
while (!quit)
{
while (SDL_PollEvent(&e) != 0)
{
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_q)
{
quit = true;
}
}
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 0);
SDL_Rect rect = { 200, 40, 400, 400 };
SDL_RenderDrawRect(renderer, &rect);
SDL_Color textColor = { 0, 0, 0 };
SDL_Surface* textSurface = TTF_RenderText_Solid(font, "HELLO", textColor);
if (textSurface == NULL)
{
printf("Error %s\n", SDL_GetError());
}
else
{
SDL_Texture* mTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
if (mTexture == NULL)
{
printf("Error %s\n", SDL_GetError());
}
else
{
SDL_Rect rectSrc = { 0, 0, textSurface->w, textSurface->h };
SDL_Rect rectDes = { 25, 25, textSurface->w, textSurface->h };
SDL_RenderCopy(renderer, mTexture, &rectSrc, &rectDes);
SDL_DestroyTexture(mTexture);
}
SDL_FreeSurface(textSurface);
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(win);
TTF_Quit();
SDL_Quit();
return 0;
}
However I’m getting the following error on line SDL_FreeSurface(textSurface);
:
Exception thrown at 0x000000005FA48159 (SDL2.dll) in TestSDL.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
This is the textSurface output at the time of error:
By removing line SDL_FreeSurface(textSurface);
the program works as intended, but then I have a memory leak.
What seems to be causing this error?
I’m using Visual studio 2022 with SDL2 2.0.22 and SDL2_ttf 2.20.0.