Fix memory deallocation and leakage