fix memory issues reported by valgrind