fix some memory leaks and a new bug