Memleak fixes

Backports of upstream memleak fixes. 
But who cares if this is a backport of someone's changes :)