C++ SDL 中的 SIGSEGV 错误



这段代码使SIGSEGV错误,我无法弄清楚为什么。

#include<SDL.h>
SDL_Window* g_pWindow = 0;
SDL_Renderer* g_pRenderer = 0;
int main(int argc, char* args[])
{
    // initialize SDL
    if(SDL_Init(SDL_INIT_EVERYTHING) >= 0)
    {
       // if succeeded create our window
       g_pWindow = SDL_CreateWindow("Chapter 1: Setting up SDL",
       SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,640, 480,SDL_WINDOW_SHOWN);
       // if the window creation succeeded create our renderer
       if(g_pWindow != 0)
       {
           g_pRenderer = SDL_CreateRenderer(g_pWindow, -1, 0);
       }
    }
    else
    {
            return 1; // sdl could not initialize
    }
    // everything succeeded lets draw the window
    // set to black // This function expects Red, Green, Blue and
    // Alpha as color values
    SDL_SetRenderDrawColor(g_pRenderer, 0, 0, 0, 255);
    // clear the window to black
    SDL_RenderClear(g_pRenderer);
    // show the window
    SDL_RenderPresent(g_pRenderer);
    // set a delay before quitting
    SDL_Delay(5000);
    // clean up SDL
    SDL_Quit();
    return 0;
}

此代码出自 Sean Mitchell 的《SDL 游戏开发》一书。但是,我使用的是mingw,而不是书中建议的Visual Studio。我已经按照lazyfoo的教程中所述配置了所有内容:http://lazyfoo.net/tutorials/SDL/01_hello_SDL/windows/mingw/index.php顺便说一句,他的"你好SDL"工作正常。这是我的制作文件:

#OBJS specifies which files to compile as part of the project
OBJS = main.cpp
#OBJ_NAME specifies the name of our exectuable
OBJ_NAME = hello
#This is the target that compiles our executable
all : $(OBJS)
    g++ $(OBJS) -IC:ArturProjectsSDLincludeSDL2 -LC:ArturProjectsSDLlib -w  -lmingw32 -lSDL2main -lSDL2 -o $(OBJ_NAME) -g

我在 gdb 中发现了什么:

(gdb) run
Starting program: C:ArturProjectsCPPSnake/hello.exe
[New Thread 4800.0x45c]
[New Thread 4800.0xc7c]
[New Thread 4800.0xc48]
[New Thread 4800.0xa8c]
[New Thread 4800.0xbc0]
[New Thread 4800.0x1350]
Breakpoint 1, SDL_main (argc=argc@entry=1, args=args@entry=0x3b0008)
    at main.cpp:17
17      g_pRenderer = SDL_CreateRenderer(g_pWindow, -1, 0);
(gdb) s
[New Thread 4800.0xf98]
Program received signal SIGSEGV, Segmentation fault.
0x00000000 in ?? <>

所以我知道SDL_CreateRenderer功能中的问题,但我不知道出了什么问题。

由于

这一行,您遇到分段错误 -

g_pRenderer = SDL_CreateRenderer(g_pWindow, -1, 0);

原因是g_pWindowNULL.正如您在此行中使用NULL初始化它时 -

SDL_Window* g_pWindow = 0;

您需要提供有效的SDL_Window指针。

有关详细信息,请查看此内容。

相关内容

  • 没有找到相关文章

最新更新