Fix bugs found by valgrind and static code analysers

This PR fixes (almost) all errors found by [scan-build](http://clang-analyzer.llvm.org/scan-build.html) plus bugs found by Valgrind (#1368, #1369, #1370, #1371)