Fix memory leaks detected based on running valgrind