Fix segfaults on program termination