Fix coverity warnings

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