c++ - SDL2 SIGSEGV 从表面创建纹理

标签 c++ textures sdl segmentation-fault

我正在尝试使用 SDL_CreateTextureFromSurface 创建 SDL_Texture。我已经多次成功地实现了这个功能,没有任何问题。目前我得到以下回溯信息:

#0  0xb7ef1e80 in ?? () from /usr/lib/libSDL2-2.0.so.0
#1  0xb7edf19c in ?? () from /usr/lib/libSDL2-2.0.so.0
#2  0xb7f12e1d in ?? () from /usr/lib/libSDL2-2.0.so.0
#3  0xb7f13ee7 in ?? () from /usr/lib/libSDL2-2.0.so.0
#4  0xb7eb2c08 in ?? () from /usr/lib/libSDL2-2.0.so.0
#5  0xb7e9f474 in SDL_CreateTextureFromSurface () from /usr/lib/libSDL2-2.0.so.0
#6  0x0805999e in Building::draw (this=0xbfffe9a8, Render=@0xbffff6d8: 0x81bd1b8)
    at /code/directory/LIBRARY.h:194
#7  0x08063df7 in main (argc=1, args=0xbffffac4) at Program.cpp:1151

我的其余代码与这个特定实现之间唯一不同的是我的 SDL_Surface 是一个指针数组,定义如下:

//<Initialize window and renderer (not included here)>
SDL_Surface** Surf;
SDL_Surface* SomeOtherSurface;
int SurfSize = 0;

SomeOtherSurface = LoadBMP("Filename.bmp");
for (i = 0; i < 2; i++)
{
    Surf = (SDL_Surface**) realloc(Surf,SurfSize+1)*sizeof(SDL_Surface*));

    SDL_LockSurface(SomeOtherSurface);
    Surf[i] = SDL_CreateRGBSurfaceFrom(SomeOtherSurface->pixels,SomeOtherSurface->w,SomeOtherSurface->h,32,SomeOtherSurface->pitch,0xFF000000,0x00FF0000,0x0000FF00,0x000000FF); //Create a surface in Surf based on SomeOtherSurface
    SDL_UnlockSurface(SomeOtherSurface);
    SurfSize++;
}
SDL_FreeSurface(SomeOtherSurface);
SDL_Texture* Tex1;
Tex1 = SDL_CreateTextureFromSurface(Render,Surf[0]); //Create the texture; this throws the SIGSEGV

我在程序的其他地方编写了类似的代码,并且没有失败;谁能弄清楚这里出了什么问题?该错误似乎表明内存有问题,但如果我尝试访问 Surf[0]->w,它会按预期返回值。

编辑:一些可以帮助解决这个问题的附加信息:在我的代码中,我在定义纹理之前释放了“SomeOtherSurface”表面。如果我在释放表面之前定义纹理,一切正常。这两个表面是否可能共享像素数据地址?

已解决:我需要使用 SDL_BlitSurface 复制数据并修改它。如果我在使用 SDL_CreateRGBSurfaceFrom 之后继续释放表面,那么当程序尝试访问该内存地址时,现有像素数据也会被删除,从而导致段错误。

最佳答案

此代码的问题在于 SDL_CreateRGBSurfaceFrom 使用现有的像素数据;因此,当您调用 SDL_FreeSurface 时,像素数据会丢失。现在,Surf[i] 在调用 SDL_CreateTextureFromSurface 时试图找到该像素数据,但内存不可访问。

解决方案:使用 SDL_BlitSurface 复制像素数据以供进一步使用。

关于c++ - SDL2 SIGSEGV 从表面创建纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907796/

相关文章:

c++ - 如何在我的 makefile 中包含目录及其所有子目录的 header ?

c++隐式转换与 double 和整数混淆

opengl - CUDA从内核直接写入OpenGL默认BackBuffer的ColorAttachment(GL_BACK)

performance - OpenGL低级性能问题

c++ - 有没有办法在 C++ 泛型类中透明地包装可比较的 C 结构?

c++ - 如何在 C++14 中衰减右值引用类型,同时保留左值引用?

c++ - SDL_VIDEORESIZE 不起作用

c++ - 内存泄漏是否有可接受的限制?

c++ - OpenGL 帧缓冲区 - 渲染到纹理

android - glDrawTex_OES 的问题