BUG: Fix memory leaks and uninitialized variables

Issues found using Valgrind.