Fix Coverity warnings

Fix resource leaks; use after free; uninitialized scalar variable; buffer overflow; etc