Fix invalid memory reads reported by valgrind leading to possible memory corruption