Various bug fixes

* Fixes lots of memory leaks
* Fixed lots of NULL pointer dereferences
* Fixes other issues found by clang scanbuild
This check is already performed by the caller.