BUG: fix memory leaks and missing NULL checks

found by cpychecker gcc plugin
Merge pull request #4578 from juliantaylor/static-bugs

BUG: fix memory leaks and missing NULL checks