title: Is sprintf(buffer, "%s […]", buffer, […]) safe?
body: <p>I saw use of this pattern to concatenate onto a string in some code I was working on:</p>
  
  <pre><code>sprintf(buffer, "%s &lt;input type='file' name='%s' /&gt;\r\n", buffer, id);
  sprintf(buffer, "%s&lt;/td&gt;", buffer);
  </code></pre>
  
  <p>and I'm fairly certain it's not safe C. You'll notice that <code>buffer</code> is both the output and the first input.</p>
  
  <p><em>Apart from the obvious possibility of a buffer overflow</em>, I believe there is no guarantee that buffer doesn't get changed between the start and the end of the function (i.e., there is no guarantee as to what the state of buffer will be during the execution of the function). The signature of sprintf additionally specifies that the target string is <code>restrict</code>ed.</p>
  
  <p>I also recall a report of a <a href="http://blogs.oracle.com/dave/entry/memcpy_concurrency_curiosities" rel="noreferrer">speculative writing in memcpy</a>, and I see no reason why some C library might do the same thing in a sprintf. In this case, of course, it would be writing to its source. So <strong>is this behaviour safe?</strong></p>
  
  <p>FYI, I proposed:</p>
  
  <pre><code>char *bufEnd = buffer + strlen(buffer);
  /* sprintf returns the number of f'd and print'd into the s */
  bufEnd += sprintf(bufEnd, " &lt;input type='file' name='%s' /&gt;\r\n", id);
  </code></pre>
  
  <p>to replace this.</p>