【发布时间】:2020-09-10 22:31:51
【问题描述】:
我有这段代码,它应该使用 SDL2_ttf 加载字体并将文本绘制到屏幕上:
结构声明:
typedef struct {
SDL_Window* win;
SDL_Event* e;
SDL_Renderer* renderer;
} SL_Window;
typedef struct {
TTF_Font* font;
char* file;
size_t size;
} SL_Font;
typedef struct {
SL_Font* font;
char* text;
SDL_Renderer* renderer;
SDL_Texture* texture;
SDL_Rect rect;
SDL_Color color;
} SL_Text;
文本渲染头:
SL_Font* SL_loadFont(const char* file, int size) {
SL_Font* font = (SL_Font*)SL_malloc(sizeof(SL_Font));
font->font = TTF_OpenFont(file, size);
if (!font->font) {
SL_log(SL_LOG_ERROR, "Error loading font \"%s\": %s", file, TTF_GetError());
SL_free(font);
return NULL;
}
size_t __size = strlen(file) + 1;
font->file = (char*)malloc(__size);
strncpy(font->file, file, __size);
}
SL_Text* SL_createText(SL_Window* window, SL_Font* font) {
SL_Text* text = (SL_Text*)SL_malloc(sizeof(SL_Text));
text->font = font;
text->renderer = window->renderer;
text->texture = NULL;
text->color.r = 0;
text->color.g = 0;
text->color.b = 0;
text->color.a = 255;
text->rect.x = 0;
text->rect.y = 0;
text->rect.w = 1000;
text->rect.h = 1000;
}
void SL_setTextString(SL_Text* text, const char* string) {
size_t __size = strlen(string) + 1;
text->text = (char*)SL_malloc(__size);
strncpy(text->text, string, __size);
SDL_Surface* surface = TTF_RenderText_Solid(text->font->font, text->text, text->color);
if (text->texture) SDL_DestroyTexture(text->texture);
text->texture = SDL_CreateTextureFromSurface(text->renderer, surface);
SDL_FreeSurface(surface);
}
void SL_windowDrawText(SL_Window* window, SL_Text* text) {
SDL_RenderCopy(window->renderer, text->texture, NULL, &text->rect);
}
...
还有主要的:
...
SL_Font* font = SL_loadFont("res/test_font.ttf", 24);
if (!font) return -1;
SL_Text* text = SL_createText(window, font);
SL_setTextString(text, "test text");
...
但每当我尝试调用 SL_setTextString(SL_Text* text, const char* string) 函数时,它都会给我 SIGBUS。它出现在SDL_Surface* surface = TTF_RenderText_Solid(text->font->font, text->text, text->color)这一行。
GDB 回溯:
#0 0x00007ffff7fa0139 in () at /lib/x86_64-linux-gnu/libSDL2_ttf-2.0.so.0
#1 0x00007ffff7fa0c4f in TTF_RenderUTF8_Solid () at /lib/x86_64-linux-gnu/libSDL2_ttf-2.0.so.0
#2 0x00007ffff7fa0fd9 in TTF_RenderText_Solid () at /lib/x86_64-linux-gnu/libSDL2_ttf-2.0.so.0
#3 0x000055555555711b in SL_setTextString (text=0x555555a52460, string=0x555555559082 "test text") at CGraphics.c:65
#4 0x0000555555556834 in main (argc=1, argv=0x7fffffffde78) at SLE_shapes.c:23
顺便说一下,我们非常感谢您列出常见的 SIGBUS 原因。
【问题讨论】:
-
总线错误通常指向一个被滥用的指针。通常,当分配指针地址而不是在指针持有的地址处设置值时(例如,忘记取消引用指针以在该地址处设置值)。从提供的代码 sn-ps 几乎不可能分辨出来。请提供A Minimal, Complete, and Verifiable Example (MCVE)。
-
检查传递给 SDL_ttf 的参数值。您的
SL_loadFont和SL_createText都错过了return声明。 -
@keltar,非常感谢您为我指出这一点。我想这是凌晨 4 点编码的问题。不过,我很困惑为什么指针指向任何地方,而不是默认为空,导致总线错误。
标签: c linux sdl sdl-ttf sigbus