第二次调用SDL_BlitSurface时出现Seg Fault

时间:2018-01-22 08:41:16

标签: c++ opengl sdl sdl-2

我正在使用SDL和SDL_Image来加载要用作opengl纹理的图像。

我正在尝试加载一个spritesheet,其中多个图像排列在一个水平行中(在同一图像中)

void load_spritesheet(std::string key, const char *file_name, int width, int height, int nframes) {
    GLuint *texture = new GLuint[nframes];
    auto src = IMG_Load(file_name);
    auto dstrect = new SDL_Rect{0, 0, width, height};

    for(int i = 0; i < nframes; i++) {
        auto dst = SDL_CreateRGBSurface(0, width, height, 1, src->format->Rmask, src->format->Gmask, src->format->Bmask, src->format->Amask);
        auto rect = new SDL_Rect { i*width, 0, width, height };
        SDL_BlitSurface(src, rect, dst, dstrect);
        load_gltex(dst, &texture[i]);
        SDL_FreeSurface(dst);
    }

    SPRITESHEET_CACHE[key] = texture;
    SDL_FreeSurface(src);
}

我逐步完成了代码,在循环的第一次迭代中,它工作正常。在第二次迭代中,我在调用SDL_BlitSurface时遇到一个seg错误,传入的指针都没有,并且没有任何表面被锁定或类似的东西。我确信我的矩形在每个表面的范围内。

以下是gdb在segfaults之前的一些值:

print i
1

print *src
{flags = 0, format = 0x847100, w = 416, h = 32, pitch = 1664, pixels = 0x87c5f0, userdata = 0x0, locked = 0, lock_data = 0x0, clip_rect = {x = 0, y = 0, w = 416, h = 32}, map = 0x8537b0, refcount = 1}

print *dst
{flags = 0, format = 0x855ec0, w = 32, h = 32, pitch = 4, pixels = 0x84d1f0, userdata = 0x0, locked = 0, lock_data = 0x0, clip_rect = {x = 0, y = 0, w = 32, h = 32}, map = 0x6bdfc0, refcount = 1}

print *rect
{x = 32, y = 0, w = 32, h = 32}

print *dstrect
{x = 0, y = 0, w = 32, h = 32}

在同一表面或同样的表面上调用SDL_BlitSurface两次是不安全的吗?感谢。

1 个答案:

答案 0 :(得分:1)

啊,错误是由于调用SDL_CreateRGBSurface

时调整深度不正确造成的

当我确实应该传递正确的值(在这种情况下为1)时,我正在传递32

一旦我纠正了段错误就消失了。

https://wiki.libsdl.org/SDL_CreateRGBSurface#Remarks