Fix bad memory access

Fix the problem `k` indicates out of the memory block.