fixed some memory problems found by Valgrind