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

r? @frank-trampe
I don't understand what was happening here.