Fix memory leaks found by using valgrind on test cases.