Fix memory off-by-one allocation bugs