fix bugs reported by running test with valgrind