Correcting invalid use-after-free error