Avoid NULL pointer dereferences
Add back NULL pointer checks accidentally dropped in r364946. We need to append a NUL character when that happens.