Fix memory errors detected by valgrind