Check index range before using it

Found buy coverity