Fixed some memory issues identified with Valgrind