Reordered frees to avoid use-after-free