SDL_Quit() 导致 SIGBUS 错误

SDL_Quit() causes SIGBUS error

从教程网站获取的以下基本 SDL2 代码引起了一些奇怪的问题:

#include <SDL2/SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define SCREENH 768
#define SCREENW 1366

SDL_Window *window = NULL;
SDL_Surface *screenSurface = NULL;
SDL_Surface *windowSurface = NULL;

int init_SDL() {
    int success = 0;
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
       printf("SDL could not initialize! ");
       printf("SDL_Error: %s\n",SDL_GetError());
       success = -1;
    }
    else {
       window = SDL_CreateWindow("SDL2_Tutorial02",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,SCREENW,SCREENH,SDL_WINDOW_SHOWN);
      if(window == NULL) {
          printf("Window could not be created! ");
          printf("SDL Error: %s\n",SDL_GetError());
      }
      else {
          screenSurface = SDL_GetWindowSurface(window);
      }
    }
    return success;
}

int loadMedia() {
    int success = 0;
    windowSurface = SDL_LoadBMP("Images/Hallo.bmp");
    if(windowSurface == NULL) {
    printf("Unable to load image! ");
    printf("SDL Error: %s\n",SDL_GetError());
    success = -1;
    }
    return success;
}

void close() {
    SDL_FreeSurface(windowSurface);
    windowSurface = NULL;
    SDL_DestroyWindow(window);
    window = NULL;
    SDL_Quit();
}

int main(int argc,char *argv[]) {
    assert(init_SDL() == 0);
    assert(loadMedia() == 0);
    SDL_BlitSurface(windowSurface,NULL,screenSurface,NULL);
    SDL_UpdateWindowSurface(window);
    SDL_Delay(3000);
    close();
    exit(EXIT_SUCCESS);
}

一旦调用位于 close() 中的 SDL_Quit(),我就会收到内存访问错误。使用 GDB 显示以下内容:

49      SDL_Quit();
(gdb) n

Program received signal SIGBUS, Bus error.
0x00007ffff68a5895 in ?? () from /usr/lib/x86_64-linux-gnu/libX11.so.6
(gdb) 

奇怪的是,当我像这样将 SDL_Quit() 放在 close() 之外时:

void close() {
    SDL_FreeSurface(windowSurface);
    windowSurface = NULL;
    SDL_DestroyWindow(window);
    window = NULL;
}

int main(int argc,char *argv[]) {
    assert(init_SDL() == 0);
    assert(loadMedia() == 0);
    SDL_BlitSurface(windowSurface,NULL,screenSurface,NULL);
    SDL_UpdateWindowSurface(window);
    SDL_Delay(3000);
    close();
    SDL_Quit();
    exit(EXIT_SUCCESS);
}

一切都很好。 SDL_Quit() 工作正常。为什么在另一个函数中调用 SDL_Quit() 时会导致 SIGBUS 错误?

编辑:此代码是在 ubuntu 14.04 上使用 gcc 和以下编译命令编译的

gcc -g3 -o tutorial tutorial.c `sdl2-config --cflags --libs` 

您的函数 close() 与同名的内部 SDL 函数冲突,导致奇怪的行为(实际上,它是 SDL 调用的 libc 标准 close() 系统调用)。

重命名您的函数,应该没问题。