Fix a null dereference bug found by static analysis.
Fix an out-of-bounds write (and resource leak) found by msvc /analyze
Fix a printf format string error found by /analyze.