Fix use-after-free bug