2 votes

Défaut de segmentation dans SDL_FillRect

J'utilise la bibliothèque SDL2, en C.

J'ai créé un programme de test pour ouvrir une fenêtre blanche, mais j'obtiens un défaut de segmentation avec la fonction SDL_FillRect bien qu'il n'y ait aucune erreur ou avertissement lorsque je le construis.

Voici le code :

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>

static const int window_width = 1000;
static const int window_height = 1000;

int main(int argc, char* argv[])
{
    //Window
    SDL_Window *window = NULL;

    //Window Surface where things will be shown
    SDL_Surface *surface = NULL;

    //Inicializar SDL
    if(SDL_Init(SDL_INIT_VIDEO) == -1)
    {
        printf("Failed to initialize SDL2. SDL Error: %s", SDL_GetError());
    }
    else
    {
        window = SDL_CreateWindow("Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, window_height, SDL_WINDOW_SHOWN );
        if(window == NULL)
            printf("Failed to create SDL2 window. SDL Error: %s", SDL_GetError());
        else
        {
            //Fill window with white color
            SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF));
            //Update surface with new changes
            SDL_UpdateWindowSurface(window);
            //Wait before closing (parameter in miliseconds)
            SDL_Delay(4000);
        }
    }
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

1voto

SiggiSv Points 1150

Vous obtenez un défaut de segmentation parce que surface est toujours NULL

Cet exemple de code est tiré directement du wiki SDL ( https://wiki.libsdl.org/SDL_FillRect ) montre comment créer un SDL_Surface avant d'appeler SDL_FillRect()

/* Declaring the surface. */
SDL_Surface *s;

/* Creating the surface. */
s = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0);

/* Filling the surface with red color. */
SDL_FillRect(s, NULL, SDL_MapRGB(s->format, 255, 0, 0));

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X