Memleak fixes

Backports of upstream memleak fixes.