Fix use-after-free bug, and better error handling