fix use-after-free crash in RT #97625

fix use-after-free crash in RT #97625 and print errors before freeing resources.