BUG: gh-2969: Backport memory leak fix 80b3a34.
Merge pull request #2983 from charris/backport-fix-memory-leak

BUG: gh-2969: Backport memory leak fix 80b3a34.