Fix memory leaks reported by valgrind