UPDATE:Check my answer for details, pointer error.
I have a function, that is supposed to load a few test assets and blit them onto screen using SDL2. This function throws a segfault immediately before executing any commands, with no clear cause. Keep in mind that some of the variables in this function are globals.
Function contents:
printf("DEBUG");
int menuSelect = 0;
printf("declare");
SDL_Surface* bg = SDL_LoadBMP("menubg.bmp");
printf("bg load");
SDL_Surface* menu1 = TTF_RenderText_Solid(font,"HACKING PROGRAM",whiteclr);
printf("title blip");
SDL_BlitSurface(bg,NULL,screen,NULL);
printf("event");
SDL_Event* event;
printf("menu2");
SDL_Surface* menu2 = TTF_RenderText_Solid(font,"Hack",whiteclr);
printf("rect");
SDL_Rect menu2r = CreateRect(5,30,menu2->w,menu2->h);
printf("free");
SDL_FreeSurface(menu2);
SDL_FreeSurface(menu1);
while(SDL_WaitEvent(event))
{
switch(event->type)
{
case SDL_MOUSEBUTTONDOWN:
if(event->motion.x > menu2r.x && event->motion.x < menu2r.x+menu2r.w && event->motion.y > menu2r.y && event->motion.y < menu2r.y+menu2r.h)
{
SDL_FreeSurface(bg);
return 0;
}
break;
case SDL_MOUSEMOTION:
if(event->motion.x > menu2r.x && event->motion.x < menu2r.x+menu2r.w && event->motion.y > menu2r.y && event->motion.y < menu2r.y+menu2r.h)
{
menuSelect=1;
}
else
{
menuSelect=0;
}
break;
}
if(menuSelect==1)
{
menu2 = TTF_RenderText_Solid(font,"Hack",selectclr);
}
else
{
menu2 = TTF_RenderText_Solid(font,"Hack",selectclr);
}
}
return 0;
Apply some basic exception handling. For example:
It's good practice to always check the outcome of your statement to make sure it worked as planned.
Also, it's
while(SDL_WaitEvent(&event))
notwhile(SDL_WaitEvent(event))
.