Fix out-of-bounds check

Fixes #2934.