I picked up on SDL not long ago and its going pretty slow so far. Here is the code in c of tutorial 3 from the lazyfoo guide. The 2 problems I am having with my code is that I am always getting a segmentation fault at the end of the execution of the code, which I dont really understand why. And seconly, my even handling is obviously borked since it is not responding to the closing of the window.
What am I doing wrong? I have to work this kink out before I move on to more advanced tutorials but I am pretty clueless whats going wrong. It is the code between line 31-52 that are handling the events for reference.
Code:
#include <SDL2/SDL.h>
//Forward declerations of functions.
int init(const char* title, int xpos, int ypos, int height, int width, int flags);
void close();
int loadmedia();
//Image screens
SDL_Window* Window = NULL;
SDL_Surface* ScreenSurface = NULL;
SDL_Surface* XOut = NULL;
int main(int argc, char* args[])
{
const int SCREEN_HEIGHT = 640;
const int SCREEN_WIDTH = 480;
int running = 0;
if(init("ATTACK!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_HEIGHT, SCREEN_WIDTH, SDL_WINDOW_SHOWN) == 0)
{
printf("SDL Failed: %s.\n", SDL_GetError());
return 1; //Something went wrong
}
else
{
if(loadmedia() == 1)
{
//Main loop flag
int quit = 0;
//Event variable
SDL_Event event;
//While application is running
while( quit == 0 )
{
//Handle events on queue
while( SDL_PollEvent( &event ) != 0 )
{
//User requests quit
if( event.type == SDL_QUIT )
{
quit = 1;
}
}
//Apply the image
SDL_BlitSurface( XOut, NULL, ScreenSurface, NULL );
//Update the surface
SDL_UpdateWindowSurface( Window );
}
}
else
{
//Image application failed.
printf("Image could be loaded: %s", SDL_GetError());
}
}
//Exit SDL
close();
return 0;
}
int init(const char* title, int xpos, int ypos, int height, int width, int flags)
{
int success = 1;
if(SDL_Init(SDL_INIT_VIDEO) == 0)
{
//If SDL_Init succeeded.
Window = SDL_CreateWindow(title, xpos, ypos, height, width, flags);
if(Window == NULL)
{
//Window creation failed!
printf("Window could not be created: %s", SDL_GetError());
success = 0;;
}
else
{
printf("Window succeded\n");
ScreenSurface = SDL_GetWindowSurface(Window);
}
}
else
{
//If SDL_Init failed!
printf("SDL init failed with error: %s", SDL_GetError());
success = 0;
}
return success;
}
int loadmedia()
{
//Loading success flag
int success = 1;
//Load splash image
XOut = SDL_LoadBMP( "image.bmp" );
if( XOut == NULL )
{
printf( "Unable to load image %s! SDL Error: %s\n", "image.bmp", SDL_GetError() );
success = 0;
}
return success;
}
void close()
{
//Deallocate surface from SDL_LoadBMP
SDL_FreeSurface( XOut );
XOut = NULL;
//Destroy window
SDL_DestroyWindow( Window );
Window = NULL;
//Quit SDL subsystems
SDL_Quit();
}