Fix memory leaks and one malloc issue