声明任何标准变量时,SDL崩溃

时间:2013-12-20 07:24:07

标签: c crash sdl sdl-2

这个SDL程序运行正常(显示窗口并在其上绘制位图),但是,如果我在程序中声明任何变量(例如int,long等),则窗口冻结并且是白色而不是黑色什么都没画。什么可能导致这种情况?

#include <stdio.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

int main(int argc, char* argv[]) {
    // line below will cause SDL crash
    // int blabla = 640; 
    SDL_Window *window;
    SDL_Init(SDL_INIT_VIDEO);
    window = SDL_CreateWindow(
        "A rather exceptional SDL window",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        640,
        480,
        SDL_WINDOW_OPENGL
    );
    if (window == NULL) {
        printf("Could not create window: %s\n", SDL_GetError());
        return 1;
    }
    SDL_Renderer *renderer;
    SDL_Texture *texture;
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_Surface *brush;
    brush = IMG_Load("brush2.png");
    texture = SDL_CreateTextureFromSurface(renderer, brush);
    SDL_RenderClear(renderer);
    SDL_Rect *sRect, *dRect;
    sRect->w = 10;
    sRect->h = 4;
    sRect->x = 0;
    sRect->y = 0;
    dRect->w = 10;
    dRect->h = 4;
    dRect->x = 10;
    dRect->y = 10;
    SDL_RenderCopy(renderer, texture, sRect, dRect);
    SDL_RenderPresent(renderer);
    SDL_Delay(1000);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

1 个答案:

答案 0 :(得分:6)

您正在编写未分配的内存。

SDL_Rect *sRect, *dRect;
sRect->w = 10; /* w doesn't exist. Writing is undefined behaviour. */

sRectdRect只是指针。在访问struct成员之前,他们需要指向有效的内存。

您可以在堆栈中声明它们:

SDL_Rect sRect, dRect;
sRect.w = 10;
sRect.h = 4;
...
SDL_RenderCopy(renderer, texture, &sRect, &dRect);

您还应该检查SDL_ - 函数的返回值。如果这些失败,并且无论如何继续执行,您可能会遇到奇怪的行为或崩溃。