Fixed memory leaks and infinity loop