Memory leak and access fixes
This is part of !3597 (merged) -- a linux debug build for CI. With help of address sanitizer several memory leaks and one dangling reference access were identified and the corrections are presented here.
Review commit-wise.