使用SDL_Texture指针时出现Segmentation fault问题求助
问题根源
你遇到的核心问题是C++的指针值传递机制:func函数中的SDL_Texture* pText是main中pText指针的一份局部副本。当你在函数内执行pText = SDL_CreateTextureFromSurface(...)时,只是修改了这个局部副本的指向,完全不会影响main函数里的原始指针。main中的pText始终是未初始化的野指针,调用SDL_QueryTexture必然会崩溃或返回无效值。
解决方案
有两种常用的修复方式,任选其一即可:
方案1:使用指针的指针(兼容C/C++)
将函数参数改为SDL_Texture** pText,通过二级指针直接修改原始指针的指向:
void func(SDL_Texture** pText, SDL_Rect* pRect, SDL_Renderer* rend){ if (!pText) return; // 空指针检查 SDL_Surface* loadSurface = IMG_Load("pic.png"); if(!loadSurface){ printf("Error creating surface. - %s", SDL_GetError()); return; // 加载失败直接返回,避免后续无效操作 } *pText = SDL_CreateTextureFromSurface(rend, loadSurface); if(!*pText){ printf("Error creating texture. - %s", SDL_GetError()); } SDL_FreeSurface(loadSurface); } // main中调用时传指针的地址 func(&pText, &pRect, rend);
方案2:使用指针引用(C++专属)
利用C++的引用特性,让函数参数直接绑定到原始指针:
void func(SDL_Texture*& pText, SDL_Rect* pRect, SDL_Renderer* rend){ SDL_Surface* loadSurface = IMG_Load("pic.png"); if(!loadSurface){ printf("Error creating surface. - %s", SDL_GetError()); return; } pText = SDL_CreateTextureFromSurface(rend, loadSurface); if(!pText){ printf("Error creating texture. - %s", SDL_GetError()); } SDL_FreeSurface(loadSurface); } // main中调用方式不变 func(pText, &pRect, rend);
额外优化建议
- 完善全链路错误处理:如果
SDL_CreateWindow或SDL_CreateRenderer失败,要及时清理资源并返回,避免内存泄漏。 - 确认
pic.png路径正确:若文件路径错误,IMG_Load会失败,后续创建纹理的操作也会失效。 - 程序结束前清理SDL资源:依次调用
SDL_DestroyTexture(pText)、SDL_DestroyRenderer(rend)、SDL_DestroyWindow(win)、SDL_Quit()释放资源。
内容的提问来源于stack exchange,提问作者nyedoardo
相关产品推荐
相关产品推荐

