Fixed bug with misplaced memory deallocation