SDL2 SIGSEGV从曲面创建纹理

时间:2015-11-25 03:02:24

标签: c++ textures sdl sigsegv

我正在尝试使用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] - &gt; w它会按预期返回值。

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

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

1 个答案:

答案 0 :(得分:1)

此代码的问题是SDL_CreateRGBSurfaceFrom使用现有的像素数据;因此,当您调用SDL_FreeSurface时,像素数据会丢失。现在,Surf [i]尝试在调用SDL_CreateTextureFromSurface时找到像素数据,并且无法访问内存。

解决方案:使用SDL_BlitSurface制作像素数据的副本以供进一步使用。