Various bug fixes

* Fixes lots of memory leaks
* Fixed lots of NULL pointer dereferences
* Fixes other issues found by clang scanbuild
Is it really needed when calloc() is used above ?