Fixing memory leaks and seg fault