2017-04-20 4 views
-1

Ich versuche, Text in einem Fenster mit sdl zu setzen C mit Ich verfolge diesen tutorial. Wenn ich Schritt für Schritt folgen, nachdem er die Oberfläche initialisieren:Segmentation Fault mit TTF-Bibliothek SDL C

SDL_Color color = { 255, 255, 255 }; 
SDL_Surface * surface = TTF_RenderText_Solid(font,"Welcome to Programmer's Ranch", color); 

Ich bekomme Segmentierung Fault. Deshalb an dieser Stelle mein Code ist dies:

#include <SDL2/SDL.h> 
#include <SDL2/SDL_image.h> 
#include <SDL2/SDL_ttf.h> 


int main(int argc, char ** argv) 
{ 
    int quit = 0; 
    SDL_Event event; 

    SDL_Init(SDL_INIT_VIDEO); 

    TTF_Init(); //Initialise ttf library 

    SDL_Window * window = SDL_CreateWindow("SDL_ttf in SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); 
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); 

    TTF_Font * font = TTF_OpenFont("arial.ttf", 25);//Load text(to put after renderere initialisation!)The first is the path to the TrueType Font (TTF) that it needs to load. The second is the font size (in points, not pixels). In this case we're loading Arial with a size of 25. 
    SDL_Color color = { 255, 255, 255 }; 
    SDL_Surface * surface = TTF_RenderText_Solid(font, "Welcome to Programmer's Ranch", color); 

    while (!quit) 
    { 
     SDL_WaitEvent(&event); 

     switch (event.type) 
     { 
      case SDL_QUIT: 
      quit = 1; 
      break; 
     } 
    } 

    TTF_CloseFont(font); 
    SDL_DestroyRenderer(renderer); 
    SDL_DestroyWindow(window); 
    TTF_Quit(); 
    SDL_Quit(); 

    return 0; 
} 

während seiner gesamten Quellcode here verfügbar ist, aber es funktioniert sowieso nicht funktionieren.

+2

Sie sollten die Rückgabewerte von Funktionsaufrufen überprüfen. Wurden insbesondere Aufrufe von 'SDL_Init()' und 'TTF_Init()' erfolgreich ausgeführt? Was ist mit 'TTF_OpenFont()'? –

Antwort

0

Es ist höchstwahrscheinlich, dass der Pfad zu arial.ttf falsch ist. Stellen Sie sicher, dass Sie den vollständigen Pfad dieser Datei aus dem Stammprojektverzeichnis angeben.

Was Sie tun sollten, ist das Hinzufügen von Ausnahmehandlern jedes Mal, wenn Sie etwas initiieren oder laden in /. Zum Beispiel:

#include <stdexcept> 

try 
{ 
    TTF_Font * font = TTF_OpenFont("arial.ttf", 25); 
    if (font == NULL) 
    { 
     throw(::std::runtime_error("Font failed to load! ERROR: ")); 
    } 
} 
catch (std::runtime_error const& msg) 
{ 
    printf("%s", msg.what()); 
    if (SDL_GetError() != NULL) 
    { 
     printf("%s", SDL_GetError()); 
    } 
    if (TTF_GetError() != NULL) 
    { 
     printf("%s", TTF_GetError()); 
    } 
}