Fix crash on shutdown (double free)

This fixes #643 (I only made the pull request, not the fix, the fix is by blue42u)