fixed write past end of buffer