Checked by Valgrind and fixed a few memory leaks.