Various bug fixes

* Fixes lots of memory leaks
* Fixed lots of NULL pointer dereferences
* Fixes other issues found by clang scanbuild
I don't like when we silently return in case of OOM, we should return an error.
Here formatList.numFormats == 0 or OOM are treated the same.