Fix memory corruption on unclean shutdown

See #2829