Fix race and leak

Sorry for submitting two commits in this pull request, but the second builds on the first.