Dangling pointer error fixed.
Refactoring