SDL_ttf文本渲染程序执行SDL_FreeSurface时触发访问冲突错误求助
SDL_ttf渲染文本时
SDL_FreeSurface触发访问冲突的原因 问题代码
#include <stdio.h> #include <SDL.h> #include <SDL_ttf.h> #include <stdbool.h> SDL_Renderer* renderer; TTF_Font* font = NULL; int main() { SDL_Init(SDL_INIT_VIDEO); SDL_Window* win = SDL_CreateWindow("Title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); // Font if (TTF_Init() < 0) { printf("Failed to initialize TTF!\n"); } font = TTF_OpenFont("arial.ttf", 12); if (!font) { printf("Failed to load font!\n"); } bool quit = false; SDL_Event e; while (!quit) { while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_q) { quit = true; } } SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 255, 0, 0, 0); SDL_Rect rect = { 200, 40, 400, 400 }; SDL_RenderDrawRect(renderer, &rect); SDL_Color textColor = { 0, 0, 0 }; SDL_Surface* textSurface = TTF_RenderText_Solid(font, "HELLO", textColor); if (textSurface == NULL) { printf("Error %s\n", SDL_GetError()); } else { SDL_Texture* mTexture = SDL_CreateTextureFromSurface(renderer, textSurface); if (mTexture == NULL) { printf("Error %s\n", SDL_GetError()); } else { SDL_Rect rectSrc = { 0, 0, textSurface->w, textSurface->h }; SDL_Rect rectDes = { 25, 25, textSurface->w, textSurface->h }; SDL_RenderCopy(renderer, mTexture, &rectSrc, &rectDes); SDL_DestroyTexture(mTexture); } SDL_FreeSurface(textSurface); } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 0); SDL_RenderPresent(renderer); } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(win); TTF_Quit(); SDL_Quit(); return 0; }
错误现象
执行SDL_FreeSurface(textSurface);时触发访问冲突:
Exception thrown at 0x000000005FA48159 (SDL2.dll) in TestSDL.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
错误发生时textSurface的状态:
触发原因
核心问题在于字体加载失败后程序未终止,导致后续使用无效指针调用TTF渲染函数:
- 当
TTF_OpenFont("arial.ttf", 12)加载失败时,font被设为NULL,但代码仅打印错误信息,未退出程序或终止渲染逻辑。 - 主循环中使用
NULL的font调用TTF_RenderText_Solid时,SDL_ttf并未返回预期的NULL,而是返回了非法指针0xFFFFFFFF(即-1)。 - 代码中的
if (textSurface == NULL)判断无法识别该非法指针,会进入else分支执行后续逻辑,最终调用SDL_FreeSurface释放非法指针,触发访问冲突。
内容的提问来源于stack exchange,提问作者Kazgaa
相关产品推荐
相关产品推荐

