Some code correctness improvements

I've just ran the library through clang's [scan-build](http://clang-analyzer.llvm.org/) tool (which is awesome, by the way), and it found a couple of problematic things.

Nothing critical, but a few memory leaks in cases of errors, and some dead assignments.