fixing bugs found by valgrind