c++ SDL项目中的分段错误

Segmentation fault in C++ SDL project

本文关键字:分段 错误 SDL 项目 c++      更新时间:2023-10-16

为什么我在这个函数中有分割错误,特别是在与DisplayFormat函数的行中?我已经遇到这个问题好几次了,不知道如何解决。

SDL_Surface* imageBlitingFunctions::loadIMG(std::string filename)
{
    SDL_Surface *img = IMG_Load(filename.c_str());
    SDL_Surface *imgOPT = SDL_DisplayFormat(img);
    SDL_FreeSurface(img);
    return imgOPT;
}

按如下方式修改代码

SDL_Surface* imageBlitingFunctions::loadIMG(std::string filename)
{
    SDL_Surface *img = IMG_Load(filename.c_str());
    if(img == NULL) {
        std::cerr << "ERROR: image load failed: " << SDL_GetError() << std::endl;
        return NULL;
    }
    SDL_Surface *imgOPT = SDL_DisplayFormat(img);
    SDL_FreeSurface(img);
    return imgOPT;
}

来克服分割错误,并获得IMG_Load()实际出错的一些信息。

也不要忘记检查函数之外的返回值不是NULL,在使用它之前