异常在0x71002A85(SDL2_ttf.dll)抛出

问题描述:

所以我创建一个使用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。 –

您应该检查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