Fix memory leaks

I used valgrind to reveal a few memory leaks and fixed them.