Null-terminate some buffers and fix a write-after-free

r? @frank-trampe