fixed segfault on exit and more valgrind issues