SDL2 segmentation fault when creating a variable error

  c++, sdl, sdl-2

i’ve been trying to learn SDL2 with c++. But i keep getting this weird error. This is a simplified version of the code that produces the error.

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

int main() {
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window *window = NULL;
    SDL_Renderer *renderer = NULL;
    SDL_Surface *screen = NULL;
    
    window = SDL_CreateWindow("Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 600, 400, SDL_WINDOW_RESIZABLE|SDL_WINDOW_BORDERLESS);
    renderer = SDL_CreateRenderer(window, -1, 0);
    screen = SDL_GetWindowSurface(window);

    Uint32 color = SDL_MapRGB(screen->format, 255, 255, 255);

    SDL_Delay(3000);

    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

I compile it with the command g++ test.cpp -o SDL2 -I include -L lib -l SDL2-2.0.0 And it compiles fine, but when i try to run the program, it just says "segmentation fault". I’ve figured out that if i remove the line that creates a variable named color,

    Uint32 color = SDL_MapRGB(screen->format, 255, 255, 255);

the program runs without any errors. I’ve also figured out that it works without errors if i remove the lines that create the renderer.

    SDL_Renderer *renderer = NULL; // this line

    renderer = SDL_CreateRenderer(window, -1, 0); // and this one

I am on MacOS Catalina if that’s important. I have no idea what causes this and i hope someone knows how to fix the error.

Source: Windows Questions C++

LEAVE A COMMENT