Fix out-of-bounds check

Fixes #2924.