启动时SDL2错误

时间:2014-04-07 18:31:18

标签: c++ sdl-2

我最近开始从SDL1.2升级/更新到SDL2,到目前为止相当容易,但我的程序现在在启动时遇到错误。我已将错误本地化为一个尝试加载.bmp图像的函数调用。任何有关我的功能无效的见解都非常感谢!

SDL_Texture *load_image(SDL_Renderer* renderer, std::string filename)
{
  SDL_Surface* loadedImage = NULL;
  SDL_Surface* optimizedImage = NULL;

  loadedImage = SDL_LoadBMP(filename.c_str());

  if(loadedImage != NULL)
  {
    //optimizedImage = SDL_DisplayFormat(loadedImage);
    optimizedImage->format = loadedImage->format;

    if(optimizedImage != NULL)
    {
        Uint32 colorkey = SDL_MapRGB(loadedImage->format, 255, 174, 201);

        SDL_SetColorKey(optimizedImage, SDL_TRUE, colorkey);
    }

    SDL_Texture* transformedImage = SDL_CreateTextureFromSurface(renderer,optimizedImage);
    SDL_FreeSurface(loadedImage);
    return transformedImage;
  }
  else
  {
    printf("Could not load image: %s\n", SDL_GetError());
    SDL_Texture* transformedImage = SDL_CreateTextureFromSurface(renderer,loadedImage);
    SDL_FreeSurface(loadedImage);
    return transformedImage;
  }
}

1 个答案:

答案 0 :(得分:1)

您的代码有错误:

/* ... */
if(loadedImage != NULL)
{
    /* ... */
}
else
{
    /* ... */
    SDL_Texture* transformedImage = SDL_CreateTextureFromSurface(renderer,loadedImage);
    /* ... */
}
/* ... */

else阻止仅在loadedImage等于NULL时执行,但您使用SDL_CreateTextureFromSurface调用/* ... */ SDL_Surface* optimizedImage = NULL; /* ... */ if(loadedImage != NULL) { //optimizedImage = SDL_DisplayFormat(loadedImage); optimizedImage->format = loadedImage->format; /* ... */ } /* ... */ 。这可能不是你想要的。


optimizedImage

NULL等于{{1}},但您可以访问其中一个成员。这会导致分段错误,并引发分段错误错误!