valgrind errors and memory leaks fixed