I'm currently trying to create a game in C++17 with SDL2 (and SDL_ttf). When I'm trying to initialize the text renderer, I'm getting an error that says: "Exception thrown at 0x00007FFFB5A19116 (SDL2_ttf.dll) in projVSC.exe: 0xC0000005: Access violation reading location 0x0000000000000060." Currently using Visual Studio Community 2022. I'm getting the error in two places:
- The game.cpp file:
void Game::init()
{
if (SDL_CreateWindowAndRenderer(1280, 720, SDL_WINDOW_RESIZABLE, &window, &renderer) < 0)
{
std::cout << "Window and Render could not be created! SDL_Error: " << SDL_GetError() << '\n';
isRunning = false;
return;
}
textRenderer = new TextRenderer(renderer, "PlayfairDisplayRegular-ywLOY.ttf", 24);
if (!textRenderer) {
std::cerr << "Failed to create text renderer." << std::endl;
isRunning = false;
return;
}
SDL_SetWindowTitle(window, "projVSC");
isRunning = true;
}
and 2. the TextRenderer.cpp file:
#include "TextRenderer.h"
#include <iostream>
TextRenderer::TextRenderer(SDL_Renderer* renderer, const std::string& fontPath, int fontSize) : renderer(renderer), font(nullptr) {
font = TTF_OpenFont(fontPath.c_str(), fontSize);
if (!font) {
std::cerr << "Failed to load font: " << TTF_GetError() << std::endl;
// Handle error (e.g., exit or throw an exception)
}
}
TextRenderer::~TextRenderer() {
if (font != nullptr) {
TTF_CloseFont(font);
}
}
void TextRenderer::renderText(const std::string& text, int x, int y, SDL_Color color) {
SDL_Surface* surface = TTF_RenderText_Solid(font, text.c_str(), color);
if (!surface) {
std::cerr << "Failed to render text: " << TTF_GetError() << std::endl;
return;
}
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_Rect renderQuad = { x, y, surface->w, surface->h };
SDL_RenderCopy(renderer, texture, nullptr, &renderQuad);
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
}
Initially the issue was it being unable to find the .ttf file, which resulted in the text renderer defaulting to the nullptr it's set as. I was able to get it to recognize the proper location of it, but while my checks no longer say it's passing a nullptr in the debugging output, It's still not able to read the text file, with the error given before, "Exception thrown at 0x00007FFFB5A19116 (SDL2_ttf.dll) in projVSC.exe: 0xC0000005: Access violation reading location 0x0000000000000060." This is my first attempt at making a game, so hopefully someone can give some insight^^.