使用 C++/SDL2 加载图像 - "unhandled exception"、"access violation reading location"

Loading images with C++/SDL2 - "unhandled exception", "access violation reading location"

我正在研究别人的早期版本的 SDL 的 Pong 代码,我正在努力获得它 运行 SDL2。下面是我的代码的摘录,它只 加载 图像。当此代码为 运行 时,我会弹出一个 window 告诉我: Pong.exe 中 0x00A065AD 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000004。 在调试时,它还指向这一行:

optimizedImage = SDL_ConvertSurface(loadedImage, windowSurface->format, 0);

错误列表显示warning LNK4098: defaultlib 'msvcrt.lib' 与其他库的使用冲突;使用 /NODEFAULTLIB:library

我不知道该怎么做。最重要的是,SDL window 出现、冻结,有时甚至在调试结束后也不会关闭。 (当我尝试时它告诉我存在访问冲突。)

#include <string>
#include <SDL.h>

const int WINDOW_WIDTH = 640;
const int WINDOW_HEIGHT = 475;
const int SCREEN_BPP = 2;

SDL_Window *window = NULL;
SDL_Surface *windowSurface = NULL;
SDL_Surface *ball = NULL;
SDL_Surface *background = NULL;
SDL_Surface *paddleL = NULL;
SDL_Surface *paddleR = NULL;

SDL_Event event;

SDL_Surface *loadImage(std::string fileName)
{
    SDL_Surface *loadedImage = NULL;
    SDL_Surface *optimizedImage = NULL;

    loadedImage = SDL_LoadBMP(fileName.c_str());

    if (loadedImage != NULL)
    {
        optimizedImage = SDL_ConvertSurface(loadedImage, windowSurface->format, 0);

        SDL_FreeSurface(loadedImage);

        if (optimizedImage != NULL)
        {
            SDL_SetColorKey(optimizedImage, SDL_TRUE,
                            SDL_MapRGB(optimizedImage->format, 255, 255, 255));
        }
    }

    return optimizedImage;
}

bool init()
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
        return false;

    window = SDL_CreateWindow("Pong", SDL_WINDOWPOS_CENTERED,
                            SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH,
                            WINDOW_HEIGHT, SDL_WINDOW_SHOWN);

    if (window == NULL)
        return false;

    return true;
}

bool loadFiles()
{
    ball = loadImage("ball.bmp");
    background = loadImage("background.bmp");
    paddleL = loadImage("paddleRed.bmp");
    paddleR = loadImage("paddleBlue.bmp");

    if (ball == NULL)
        return false;

    if (background == NULL)
        return false;

    if (paddleL == NULL || paddleR == NULL)
        return false;

    return true;
}

int main(int argc, char* args[])
{
    windowSurface = SDL_GetWindowSurface(window);

    if (init() == false)
        return 1;
    if (loadFiles() == false)
        return 1;

    SDL_FreeSurface(windowSurface);
    SDL_FreeSurface(ball);
    SDL_FreeSurface(background);
    SDL_FreeSurface(paddleL);
    SDL_FreeSurface(paddleR);
    windowSurface = ball = background = paddleL = paddleR = nullptr;
    SDL_DestroyWindow(window);
    window = nullptr;

    SDL_Quit();
    return 0;
}

您正在呼叫

windowSurface = SDL_GetWindowSurface(window);

之前

window = SDL_CreateWindow("Pong", SDL_WINDOWPOS_CENTERED,

所以window还是会为NULL,导致windowSurface为NULL,导致windowSurface->format导致崩溃