Fix some memory freeing issues
Fix valgrind errors