c - SDL_Quit() 导致 SIGBUS 错误

标签 c sdl

以下从教程网站获取的基本 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 函数冲突导致奇怪的行为(实际上,它是调用的 libc 标准 close() 系统调用由 SDL)。

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

关于c - SDL_Quit() 导致 SIGBUS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32976279/

相关文章:

在 C 中创建多个线程 : write pid, tid 并返回整数

c++ - SDL2 丢失 OpenGL 上下文或函数未定义

c++ - SDL/C++ OpenGL 程序,如何阻止 SDL 捕获 SIGINT

c++ - 如何在 C++ 中通过引用分配类实例?

c - K22F 上的 I2C 初始化作为主机

c - 如果数组中存在 0 到 n-1 范围内的所有元素,则返回 0 或 1 的函数,运行时间 O(n)

c - openssl:使用 3gpp testvectors 的 128 位 key 的 c 中 aes ctr 方法的解密输出问题

c - 如何为结构体的字段动态分配内存?

c++ - 如何创建 SDL 弹出菜单?

c++ - 程序在 SDL 中立即关闭