I have the following simple SDL code:
#include <SDL.h>
#include <stdbool.h>
#include <stdio.h>
// helpers
bool init(SDL_Window **win, SDL_Surface **surf) {
int const width = 800;
int const height = 600;
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
return false;
}
*win = SDL_CreateWindow("Picture test",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
width, height, 0);
if (*win == NULL) {
fprintf(stderr,
"Unable to create window: %s\n",
SDL_GetError());
return false;
}
*surf = SDL_GetWindowSurface(*win);
return true;
}
bool load_media(SDL_Surface **surf) {
*surf = SDL_LoadBMP("./sample.bmp");
if (*surf == NULL) {
fprintf(stderr, "Unable to load data: %s\n", SDL_GetError());
return false;
}
return true;
}
void close(SDL_Window **win, SDL_Surface **surf) {
SDL_FreeSurface(*surf);
SDL_DestroyWindow(*win);
SDL_Quit();
}
int main()
{
SDL_Window *win;
SDL_Surface *surf;
SDL_Surface *img;
if (!init(&win, &surf)) {
return EXIT_FAILURE;
}
if (!load_media(&img)) {
return EXIT_FAILURE;
}
SDL_BlitSurface(img, NULL, surf, NULL);
SDL_UpdateWindowSurface(win);
SDL_Delay(2000);
close(&win, &img);
}
My code always segfaults on close
(the origin of the segfault according to GDB is the line SDL_FreeSurface(*surf)
). More strangely, if I replace the call to close
with its definition, this still segfaults in exactly the same place. Specifically, if I replace close(&win, &img)
with:
SDL_FreeSurface(img);
SDL_DestroyWindow(win);
SDL_Quit();
the code still segfaults at exactly the same place, even though that function is not even being called. Only if I remove the entire close
function does this work correctly. I am completely confused as to what could be causing this.