Fix writing past the end of buffer error