Refactoring deal with memory leaks