BUG: fix memory leaks and missing NULL checks

found by cpychecker gcc plugin