Fix potential use-after-free bugs.