0
\$\begingroup\$

Whenever I move my mouse below where the image renders in my game, the SDL window crashes and closes down.

I have narrowed the crash down to the bit of code where I check to see if the Escape key was pressed and quit my game; the relevant part of my event loop is:

while (SDL_PollEvent(&e))
{
  if (e.type == SDL_QUIT)
  {
    quit = true;
  }
  if (e.key.keysym.sym == SDLK_ESCAPE)
  {
    quit = true;
  }
}

I found that if I remove the if(e.key.keysym.sym... check, the crashing stops. What is wrong with my code?

\$\endgroup\$
3
  • \$\begingroup\$ This question appears to be off-topic because it is about debugging your code for you. Please consider revising your question to include more details about the context under the bug occurs, what you have tried, what your debugger is telling you, and so on. \$\endgroup\$
    – user1430
    Jan 31, 2014 at 1:35
  • \$\begingroup\$ @JoshPetrie when I remove if (e.type == SDL_QUIT) { quit = true; } if (e.key.keysym.sym == SDLK_ESCAPE) { quit = true; } it stops crashing \$\endgroup\$ Jan 31, 2014 at 1:49
  • \$\begingroup\$ In the future, I would recommend as your next step that you then put a breakpoint there and start examining data to see why you might be getting a crash. That might lead you to discover that e.key.keysym was full of garbage data when you move the mouse (and get a mouse-up event instead of a key event). \$\endgroup\$
    – user1430
    Jan 31, 2014 at 1:59

1 Answer 1

1
\$\begingroup\$

The SDL_Event type is a union. Only a single member of the union can be active at any point in time. Your crash is likely because you are accessing the key member when it isn't the active member.

The proper way to do this is to check the event's type field before accessing the rest of it: if (e.type == SDL_KEYDOWN && e.key.keysym.sym...)

In practice you'll probably want a switch statement in there as the number of events you have grows.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .