Fixed memory leaks and error handling