fix possible buffer overflow (which can lead in stack overwrite) caused by ignoring buffer length in write-loop.