-1

I have a problem with crashing my programme when handling events in SDL2.

I handle events like this:

const Uint8 *key_buttons;

SDL_Event e;

while (SDL_PollEvent(&e))
{
  switch(e.type)
  {
    case SDL_QUIT:
      running = false;
      break;

    case SDL_KEYDOWN:
      key_buttons = SDL_GetKeyboardState(0);
      break;   

    case SDL_KEYUP:
      key_buttons = SDL_GetKeyboardState(0);
      break; 
  }
}

And then, when I call this function:

bool Get_KeyButtonState(SDL_Scancode key)
{
  if (!key_buttons)
    return false;

  if (key_buttons[key])
    return true;
  else
    return false;
}

My programme crashes.

If I call SDL_GetKeyboardState() at start of the while loop and stop using SDL_KEYDOWN and SDL_KEYUP, then my programme works.

So, my question is: why it happens and what's the proper solution? And also, is there a way how to handle just change of a state without needing to save previous state of all buttons (cause I couldn't find any function for this)?

genpfault
  • 51,148
  • 11
  • 85
  • 139
the_Imp
  • 73
  • 6
  • 2
    I know nothing about SDL, and yet that program looks highly suspect. You have an uninitialized pointer, so accessing `key_buttons` without initializing it is undefined behavior. That means that your attempt of removing those two mouse cases results in undefined behavior. Second, how can you guarantee that `key_buttons` has at least `key + 1` entries? You just assume it does without testing for it? – PaulMcKenzie Nov 17 '15 at 17:13
  • Thank you! You were right, I forget to initialize the key_buttons, now it seems everything works properly (the evil C++). – the_Imp Nov 17 '15 at 17:22

1 Answers1

0

The solution is just giving an initial NULL:

const Uint8 *key_buttons = NULL; // or 0

This ensure that your if (!key_buttons) return false; will work in all cases.

BTW, the const is confusing. In this case, it means the "value that the pointer points to" is immutable, but the "pointer itself" is mutable.

Alan Zhiliang Feng
  • 1,774
  • 18
  • 20