Backport of leak fix for #1129