Fix out-of-bounds memory access in encoder