Cleaning up memory leaks detected by valgrind