title: Proper way to replace string prefix in C
body: <p>My goal is to replace the first <code>n</code> (3) characters in a string without getting any compiler warnings or triggering undefined behavior:</p>
  <pre><code>const char *replacment = &quot;abc&quot;;
  char buffer[128] = &quot;xxx-remainder&quot;;
  </code></pre>
  <p>I am using gcc (GCC) 9.2.0 with just the standard library:</p>
  <ol>
  <li><p>Using <code>sprintf</code> appears to be inserting the NUL character in <code>replacement</code> even through I think I'm telling it not to:</p>
  <pre><code>sprintf(buffer, &quot;%.3s&quot;, replacement);
  printf(&quot;%s\n&quot;, buffer);   /// prints &quot;abc&quot;, not &quot;abc-remainder&quot;
  </code></pre>
  </li>
  <li><p>Using <code>strncpy</code> raises a warning:</p>
  <pre><code>strncpy(buffer, replacement, 3);
  </code></pre>
  <p>This triggers the following warning:</p>
  <pre><code>test.c: In function 'main':
  main.c:8:5: warning: 'strncpy' output truncated before terminating nul copying 3 bytes from a string of the same length [-Wstringop-truncation]
   8 |         strncpy(buffer, replacement, 3);
     |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~
  </code></pre>
  <p>The output appears fine in this case.</p>
  </li>
  <li><p>Of course, I can copy the characters manually using a <code>for</code> loop, but I'm trying to avoid that.</p>
  </li>
  </ol>
  <p>How do I fix either of the approaches shown here, or what alternative function call would allow me to replace the first 3 characters without inserting a NUL into the string or getting warnings?</p>