# Why does my SDL code crash when I move the mouse over the window?

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?

• 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. – user1430 Jan 31 '14 at 1:35
• @JoshPetrie when I remove if (e.type == SDL_QUIT) { quit = true; } if (e.key.keysym.sym == SDLK_ESCAPE) { quit = true; } it stops crashing – saloomi2012 Jan 31 '14 at 1:49
• 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). – user1430 Jan 31 '14 at 1:59

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...)