【问题标题】:Segmentation Fault in SDL_FillRectSDL_FillRect 中的分段错误
【发布时间】:2017-10-26 08:40:14
【问题描述】:

我正在使用 C 语言的 SDL2 库。

我编写了一个测试程序来打开一个白色窗口,但是我使用函数 SDL_FillRect 出现了分段错误,即使我在构建它时没有错误或警告。

代码如下:

#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;
}

【问题讨论】:

  • 你传入surface(设置为NULL)作为SDL_FillRect的第一个参数,可能是问题wiki.libsdl.org/SDL_FillRect跨度>
  • 嗯,好的。那我该如何通过呢?
  • 创建一个表面,如链接中的示例代码所示。 SDL_Surface *surface = SDL_CreateRGBSurface(0, window_width, window_height, 32, 0, 0, 0, 0);
  • “即使我构建它时没有错误或警告......” 准备好继续进行。您将看到的大多数错误都是这样的错误,您在构建程序时不会遇到任何错误,但程序仍然是错误的,并且在您运行时无法正常工作。
  • 是的,感谢您的提醒。真实的故事,这样的事情不是第一次发生,好吧。无论如何,我对以下答案的评论解释了我做错了什么

标签: c debugging segmentation-fault sdl-2


【解决方案1】:

您得到分段错误,因为 surface 仍然是 NULL

此示例代码直接取自 SDL wiki (https://wiki.libsdl.org/SDL_FillRect),展示了如何在调用 SDL_FillRect() 之前创建 SDL_Surface

/* 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));

【讨论】:

  • 感谢您的帮助,我刚刚意识到我忘记了 SDL_FillRect 之前的 SDL_GetWindowSurface 函数。不确定这和 SDL_CreateRGBSurface 之间有什么区别(后者没有完全解决问题:不会显示表面,尽管它确实结束了段错误),但会深入研究它。我按照本教程进行操作,以防有人感兴趣:lazyfoo.net/tutorials/SDL/01_hello_SDL/index2.php
猜你喜欢
  • 2014-04-23
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 2016-02-15
  • 2021-06-10
  • 2013-09-16
相关资源
最近更新 更多