fix bugs detected by valgrind