Fix an assert fail, and handle some potential memory leaks