SDL_ttf throws an exception after 4 minutes

Hi everyone. I have been working on a small project, however I am having one particular issue. After 4 minutes of debugging, sdl2_ttf.dll throws an exception. The exception is being thrown at this particular line

SDL_Surface* tSurface = TTF_RenderText_Solid(tfont, Score.c_str(), colour);

Visual Studio gives this error

Exception thrown at 0x7120212B (SDL2_ttf.dll) in SDL2FlappyBird.exe: 0xC0000005: Access violation reading location 0x00000004.

The source code is as follows:

void Game::render() {
TTF_Init();
TTF_Font* tfont = TTF_OpenFont(“PixelGameFont.ttf”, 24);
const std::string Score = std::to_string(score_);

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff);
SDL_RenderClear(renderer);

const SDL_Color colour = { 0xff, 0xff, 0xff, 0xff };
SDL_Surface* tSurface = TTF_RenderText_Solid(tfont, Score.c_str(), colour);
SDL_Surface* skySurface = IMG_Load("FlappySky.png");
SDL_Surface* texSurface = IMG_Load("Flappy.png");

SDL_Texture* texScore = SDL_CreateTextureFromSurface(renderer, tSurface);
SDL_Texture* sky = SDL_CreateTextureFromSurface(renderer, skySurface);
SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, texSurface);

SDL_Rect rSky = { 0, 0, 720, 720 };
SDL_Rect fSky = { 20.f, y_ + 720 / 2, 40.f, 40 };
SDL_Rect tSky = { 0, 0, 64, 64 };

SDL_RenderCopy(renderer, sky, nullptr, &rSky);


pipeA.draw(renderer);
pipeB.draw(renderer);
pipeC.draw(renderer);

gameCheck(pipeA);
gameCheck(pipeB);
gameCheck(pipeC);

SDL_RenderCopy(renderer, tex, nullptr, &fSky);
SDL_RenderCopy(renderer, texScore, nullptr, &tSky);

SDL_DestroyTexture(tex);
SDL_DestroyTexture(sky);
SDL_DestroyTexture(texScore);

SDL_FreeSurface(tSurface);
SDL_FreeSurface(skySurface);
SDL_FreeSurface(texSurface);

SDL_RenderPresent(renderer);

}

One important detail to note is that this was coded the same way another project was, which does not have the same issue.

I’ve figured out that the problem is there is a memory leak, but I am unsure as to why. I am freeing my surfaces and destroying my textures so there is no reason for there to be a memory leak but there is.

You’re initializing the TTF library (by calling TTF_Init()) and also loading a font (by calling TTF_OpenFont()) every time Game::render() is called, which I assume is every single frame. You will probably understand why that’s a problem.

The initialization of the TTF library and loading of font file(s) should happen at the startup/loading phase of your program/game only.
Then, at program/game shutdown or during some unloading phase, at a scene change for example, the TTF font should be unloaded/destroyed by calling TTF_CloseFont() and, if needed, shutdown/unload/destroy the TTF library by calling TTF_Quit().
During the runtime of the program/game, no initializing or loading of files should occur, if it’s not totally necessary.