SDL_FillRect中的SDL2 Segfault

时间:2014-04-14 20:49:26

标签: c++ linux segmentation-fault sdl-2

终端输出:

    > ./a.out 
    bla1
    Speicherzugriffsfehler

Speicherzugriffsfehler在德语中基本上意味着分段错误。

当我使用全局变量,或者将函数中的代码复制到main中时,它才起作用。我不知道它为什么会破碎。

在Linux Mint 16上编译:g ++ sdl.cpp -lSDL2

源代码:

#include <iostream>
#include <SDL2/SDL.h>

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

using namespace std;

bool init_SDL(SDL_Window *window, SDL_Surface *windowSurface);
void close_SDL(SDL_Window *window, SDL_Surface *image);

int main(int argc, char *argv[])
{
    SDL_Window *window = NULL;
    SDL_Surface *windowSurface = NULL;
    SDL_Surface *image = NULL;

    if(!init_SDL(window, windowSurface)){
        cout << "Failed to initialize SDL" << endl;
    }
    else{
        cout << "bla1" << endl;
        SDL_FillRect(windowSurface, NULL, SDL_MapRGB(windowSurface->format, 0xFF, 0xFF, 0xFF));
        cout << "bla2" << endl;
        SDL_UpdateWindowSurface(window);
        cout << "bla3" << endl;
        SDL_Delay(2000);
    }
    close_SDL(window, image);

    EXIT_SUCCESS;
}

bool init_SDL(SDL_Window *window, SDL_Surface *windowSurface){
    bool success = true;
    if(SDL_Init(SDL_INIT_VIDEO) < 0){
        cout << "SDL failed to initialize! SDL_Error: " << SDL_GetError() << endl;
        success = false;
    }
    else{
        window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if(window == NULL){
            cout << "Failed to create window! SDL_Error: " << SDL_GetError() << endl;
            success = false;
        }
        else{
            windowSurface = SDL_GetWindowSurface(window);
        }
    }
    return success;
}

void close_SDL(SDL_Window *window, SDL_Surface *image){
    SDL_FreeSurface(image);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return;
}

1 个答案:

答案 0 :(得分:1)

我在reddit上得到了解决方案。 这解决了它:

bool init_SDL(SDL_Window *&window, SDL_Surface *&windowSurface)

我需要通过引用传递指针,因为指针本身会在函数中被操纵。否则他们仍然会在main中指向null。