Fix invalid memory access warnings reported by valgrind