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

r? @frank-trampe
This could run the full length of the buffer as above, no?