fix memory leaks and errors found by valgrind