fixed valgrind errors and mem leaks