Coverity fixes

This fixes a few problems pointed out by the coverity scan including missing checks for OOM, not checking error codes, memory leaks etc.

This doesn't fix nearly all of the problems but does address lots of the low hanging fruit.
This is the first thing that gets executed in the function. There is nothing to free.