fix memory errors discoverd by valgrind