fixed several memory leaks and memory allocation issues