2016-05-12 117 views
-1

所以我創建一個使用SDL2和C++(我完全新本!)一切都進行得很順利,直到我打這個錯誤2D乒乓球比賽:異常在0x71002A85(SDL2_ttf.dll)拋出

Exception thrown at 0x71002A85 (SDL2_ttf.dll) in 2D Game.exe: 0xC0000005: Access violation reading location 0x00000000. 

代碼中斷:

SDL_Surface * surf = TTF_RenderText_Blended(font,message.c_str(),color);

#include "utilities.h" 

#include <SDL.h> 
#include <SDL_ttf.h> 

void renderTexture(SDL_Texture* tex, 
     SDL_Renderer* ren, SDL_Rect dst, SDL_Rect *clip) { 
    SDL_RenderCopy(ren, tex, clip, &dst); 
} 

void renderTexture(SDL_Texture* tex, 
     SDL_Renderer* ren, int x, int y, SDL_Rect* clip) { 
    SDL_Rect dst; 
    dst.x = x; 
    dst.y = y; 
    if (clip != nullptr) { 
     dst.w = clip->w; 
     dst.h = clip->h; 
    } else { 
     SDL_QueryTexture(tex, nullptr, nullptr, &dst.w, &dst.h); 
    } 

    renderTexture(tex, ren, dst, clip); 
} 

SDL_Texture* renderText(const std::string &message, 
    const std::string &fontFile, SDL_Color color, 
    int fontSize, SDL_Renderer* renderer) { 

    TTF_Font* font = TTF_OpenFont(fontFile.c_str(), fontSize); 

SDL_Surface* surf = TTF_RenderText_Blended(font, message.c_str(), color); 

SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surf); 

SDL_FreeSurface(surf); 
TTF_CloseFont(font); 

return texture; 

} 
+3

您沒有測試TTF_OpenFont返回的錯誤。 'font'可能是NULL。 – user4581301

+0

執行代碼時'fontFile'的值是多少? – Pierre

+0

值爲「FFFFORWA.TTF」我也剛剛注意到'font'的值爲NULL。 –

回答

0

您應該檢查font之前在行上返回的對象爲null。如果TTF_OpenFont無法打開給定的字體文件,它很有可能返回null。

TTF_Font* font = TTF_OpenFont(fontFile.c_str(), fontSize); 

if(!font) { 
    ... //some action here, perhaps throw exception 
} 
SDL_Surface* surf = TTF_RenderText_Blended(font, message.c_str(), color); 
+2

同意,這可能是原因。肯定從這裏開始,但我們不能確定這是答案,因爲OP提供的代碼太少,無法提供明確的答案。 'font'可能會很好,而且屏幕外的東西配置不好。 – user4581301