Fix various memory access problems detected by valgrind