<story><title>Beware of strncpy and strncat</title><url>https://eklitzke.org/beware-of-strncpy-and-strncat</url></story><parent_chain><item><author>tlb</author><text>Beware of the &amp;quot;correct&amp;quot; solutions proposed here.&lt;p&gt;&lt;pre&gt;&lt;code&gt;  &amp;#x2F;&amp;#x2F; OK: correctly copy src
  char dest[8];
  strncpy(dest, src, sizeof(dest) - 1);
&lt;/code&gt;&lt;/pre&gt;
With a long src, it fails to null-terminate dest. dest[7] will be whatever the contents of uninitialized memory were, so reading dest as a string is likely to run past the end.&lt;p&gt;strlcpy has a better API, though sadly it&amp;#x27;s not standard on Linux.</text></item></parent_chain><comment><author>majke</author><text>should  be either&lt;p&gt;&lt;pre&gt;&lt;code&gt;  char dest[8] = {0};
  strncpy(dest, src, sizeof(dest) - 1);
&lt;/code&gt;&lt;/pre&gt;
or&lt;p&gt;&lt;pre&gt;&lt;code&gt;  char dest[8];
  strncpy(dest, src, sizeof(dest) - 1);
  dest[sizeof(dest)-1] = &amp;#x27;\0&amp;#x27;;

&lt;/code&gt;&lt;/pre&gt;
On the same note I always wondered what &amp;quot;snprintf&amp;quot; does. That is - will it ALWAYS zero terminate (given non-NULL buffer, of size &amp;gt; 0)?</text></comment>
<story><title>Beware of strncpy and strncat</title><url>https://eklitzke.org/beware-of-strncpy-and-strncat</url></story><parent_chain><item><author>tlb</author><text>Beware of the &amp;quot;correct&amp;quot; solutions proposed here.&lt;p&gt;&lt;pre&gt;&lt;code&gt;  &amp;#x2F;&amp;#x2F; OK: correctly copy src
  char dest[8];
  strncpy(dest, src, sizeof(dest) - 1);
&lt;/code&gt;&lt;/pre&gt;
With a long src, it fails to null-terminate dest. dest[7] will be whatever the contents of uninitialized memory were, so reading dest as a string is likely to run past the end.&lt;p&gt;strlcpy has a better API, though sadly it&amp;#x27;s not standard on Linux.</text></item></parent_chain><comment><author>bitwize</author><text>The C11 Annex K functions, strcpy_s et al., have a better API than even strlcpy, and are (an optional) part of the C11 standard. They are what you should be using.</text></comment>