Fixes possible crashes on exit