Search code examples
c++visual-c++sdlaccess-violationsdl-ttf

C++ Access violation when using SDL_ttf with SDL and SDL2


I am using SDL2_ttf with SDL2 (in Visual Studio 2015). When I tried to run the following code,

#include "SDL.h"
#include "SDL_ttf.h"

int main(int argc, char* args[]) {
    SDL_Init(SDL_INIT_EVERYTHING);
    TTF_Init();

    SDL_Window* window;
    SDL_Renderer* renderer;
    SDL_CreateWindowAndRenderer(1600, 900, SDL_WINDOW_OPENGL, &window, &renderer);

    TTF_Font* font = TTF_OpenFont("comic.ttf", 12);
    SDL_Color color = { 0, 0, 0, 255 };
    SDL_Surface* textSurface = TTF_RenderText_Solid(font, "asdf", color);
    SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, textSurface);

    TTF_Quit();
    SDL_Quit();
    return 0;
}

I got a "SDL.dll missing" runtime error. I put SDL.dll, alongside SDL2.dll, libfreetype-6.dll, SDL_ttf.dll, zlib1.dll and other libraries in my system32 folder, which solved the runtime error, but I instantaneously ran into another error: "Unhandled exception at 0x000000006C812E39 (SDL2.dll) in MCP2016.exe: 0xC0000005: Access violation reading location 0x000000010000006A."

When I decided to "Break" in the Visual studio dialog telling me this, it pointed to the line

SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, textSurface);

I came across an old forum post that suggested that SDL_ttf and SDL2 can cause access violations like this because they are not completely compatible. I think this has to do something with the problems I have, since it complained about SDL.dll first. It was suggested to recompile the DLL with the SDL2 header files, but I am afraid that is beyond my competence, especially because windows and C++ do not get along very well.

I have been working on this for about eight hours now and I am running out of ideas to try to solve this. Does anyone have any ideas about this?


Solution

  • SDL and SDL2 are not compatible. You either have one, or the other.

    As mentioned in the comments, the fix is to use SDL2_ttf instead.