fix same memory management errors found with valgrind