Fixing memory leaks found by valgrind