-
Segmentation Fault
Code:
Main.cpp
#include "CSDL.h"
CSDL sdl;
int main(int argc, char *argv[])
{
SDL_Surface *screen;
sdl.InitSDL();
sdl.SetVidMode(screen);
sdl.FillRect(screen, 0, 0, _WIDTH, _HEIGHT, 45, 45, 45);
sdl.UpdateScreen(screen);
return 0;
}
Code:
FillRect function
//Fills a rect (x, y, w, h) with color (r, g, b) on screen (screen)
void CSDL::FillRect(SDL_Surface *screen, int x, int y, int w, int h, Uint8 r, Uint8 g, Uint8 b)
{
dst.x = x;
dst.y = y;
dst.w = w;
dst.h = h;
SDL_FillRect(screen, &dst, SDL_MapRGB(screen->format, r, g, b));
return;
}
I get a segmentation fault on calls to sdl.FillRect();
Any ideas why?
Full Source:
-
A segmentation fault is caused when you try to access an invalid pointer. Unless sdl.SetVidMode(screen) manages to point screen to a valid location in memory with the correct values (which isn't likely unless SetVidMode takes a reference to a pointer so that it can properly modify the pointer passed to it instead of a copy), FillRect is working with an uninitalized pointer. That will most likely cause problems.
-
This is the problem.
Code:
void CSDL::SetVidMode(SDL_Surface *screen)
{
screen = SDL_SetVideoMode(_WIDTH, _HEIGHT, _BPP, SDL_SWSURFACE);
return;
}
Have to run, but others will help you out now that the culprit code is posted.
gg
-
>This is the problem.
You actually download files? I pretty much ignore questions that only give an attached file. ;)
>screen = SDL_SetVideoMode(_WIDTH, _HEIGHT, _BPP, SDL_SWSURFACE);
This will not work. screen is passed to SetVidMode by pointer, but pointers are passed by value. In other words, the screen you assign to in SetVidMode is a copy of the pointer you passed to SetVidMode in main. You change the copy, but the original remains uninitialized. This can be fixed by passing a pointer to the pointer:
Code:
void CSDL::SetVidMode(SDL_Surface **screen)
{
*screen = SDL_SetVideoMode(_WIDTH, _HEIGHT, _BPP, SDL_SWSURFACE);
return;
}
...
#include "CSDL.h"
CSDL sdl;
int main(int argc, char *argv[])
{
SDL_Surface *screen;
sdl.InitSDL();
sdl.SetVidMode(&screen);
sdl.FillRect(screen, 0, 0, _WIDTH, _HEIGHT, 45, 45, 45);
sdl.UpdateScreen(screen);
return 0;
}
Or as a reference to a pointer:
Code:
void CSDL::SetVidMode(SDL_Surface *&screen)
{
screen = SDL_SetVideoMode(_WIDTH, _HEIGHT, _BPP, SDL_SWSURFACE);
return;
}
...
#include "CSDL.h"
CSDL sdl;
int main(int argc, char *argv[])
{
SDL_Surface *screen;
sdl.InitSDL();
sdl.SetVidMode(screen);
sdl.FillRect(screen, 0, 0, _WIDTH, _HEIGHT, 45, 45, 45);
sdl.UpdateScreen(screen);
return 0;
}
-
Thanks prelude and codeplug, never was too good at pointers... or classes for that matter, or cpp, or.... :)
Guess i waited to long to learn them.