cherry-pick some memleak fixes from master to bobtail

Cherry-pick 5 patches to fix memory leaks from master to bobtail.