Fix crash & memleaks on exit