fix off-by-one error and related segfault