3.5.x: Memory leak fixes

Has passed tests in master, so should be safe to merge into 3.5.x.