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\$
  • \$\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\$ – Josh Jan 31 '14 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\$ – saloomi2012 Jan 31 '14 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\$ – Josh Jan 31 '14 at 1:59
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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.