Fix a number of crashes on exit