Fix memory leaks

Used valgrind to locate an remove some memory leaks.