Refactored the previous memleak fix

to avoid usage of a freed pointer. Thanks Laruence )