Reputation: 21
Terminal output:
> ./a.out
bla1
Speicherzugriffsfehler
Speicherzugriffsfehler means basically Segmentation fault in german.
When i used global variables, or copypasted the code in the functions into main it just worked. I have no idea why its broken.
Compiled on Linux Mint 16 with: g++ sdl.cpp -lSDL2
Source code:
#include <iostream>
#include <SDL2/SDL.h>
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
using namespace std;
bool init_SDL(SDL_Window *window, SDL_Surface *windowSurface);
void close_SDL(SDL_Window *window, SDL_Surface *image);
int main(int argc, char *argv[])
{
SDL_Window *window = NULL;
SDL_Surface *windowSurface = NULL;
SDL_Surface *image = NULL;
if(!init_SDL(window, windowSurface)){
cout << "Failed to initialize SDL" << endl;
}
else{
cout << "bla1" << endl;
SDL_FillRect(windowSurface, NULL, SDL_MapRGB(windowSurface->format, 0xFF, 0xFF, 0xFF));
cout << "bla2" << endl;
SDL_UpdateWindowSurface(window);
cout << "bla3" << endl;
SDL_Delay(2000);
}
close_SDL(window, image);
EXIT_SUCCESS;
}
bool init_SDL(SDL_Window *window, SDL_Surface *windowSurface){
bool success = true;
if(SDL_Init(SDL_INIT_VIDEO) < 0){
cout << "SDL failed to initialize! SDL_Error: " << SDL_GetError() << endl;
success = false;
}
else{
window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if(window == NULL){
cout << "Failed to create window! SDL_Error: " << SDL_GetError() << endl;
success = false;
}
else{
windowSurface = SDL_GetWindowSurface(window);
}
}
return success;
}
void close_SDL(SDL_Window *window, SDL_Surface *image){
SDL_FreeSurface(image);
SDL_DestroyWindow(window);
SDL_Quit();
return;
}
Upvotes: 1
Views: 585
Reputation: 21
I got the solution on reddit. This solved it:
bool init_SDL(SDL_Window *&window, SDL_Surface *&windowSurface)
I needed to pass the pointers by reference, because the pointers itself get manipulated in the functions. Otherwise they would still point to null in main.
Upvotes: 1