correct memory bugs revealed using valgrind