Fixed memory errors and leaks exposed by Valgrind.