SDL_GetKeyboardState sounds dangerous if it works the way I think it does. What am I thinking wrong?

I’m kind of a beginner 'round these parts, and I was following a tutorial about getting the keyboard state. In the documentation for SDL_GetKeyboardState(), it is mentioned that:

The pointer returned is a pointer to an internal SDL array. It will be valid for the whole lifetime of the application and should not be freed by the caller.

If that’s true, wouldn’t calling SDL_GetKeyboardState every frame to check for input quickly bloat up the heap? In a 60 FPS game, getting a 512 byte response every frame would result in 30 kilobytes per second, almost two megabytes per minute, that’s adds up quick!
So there’s no way it works the way I think it does, right?
Am I missing some optimisation magic in the background here that makes it work, or just interpreting the documentation wrong? Maybe it’s only tracking the differences in keyboard state? Even then, however, I’d imagine mashing the keyboard for a while would add a lot of memory to the heap as well.

The function simply returns a pointer to an already existing array, so no new allocation is done. You can check how it works in the source code(line 961).

1 Like

Ah, so there’s one array that continuously gets updated, rather than new arrays each time. That makes sense!
In that case, I think the line from the documentation…

a snapshot of the current state of the keyboard.

…isn’t really accurate, since that’d be a very lively snapshot!

As mentioned above, it returns the same pointer every time.

So calling it every frame is OK, but I think you can even just only call it once and just keep the pointer around. Either way will work just fine.

1 Like

Well, when you call SDL_GetKeyboardState(), it’s the snapshot, but it might change the next time SDL_PumpEvents() is called (either directly by you or implicitly when calling SDL_PollEvent(), for example)

1 Like