fix bugs found by valgrind