Fix a memory leak, as well as a possible race condition.