Fix heap corruption

Fixes #1024