3.7. strncpy

char *strncpy( char * restrict s1, const char * restrict s2, size_t n);
strncpy copies at most n characters of string s2 to s1, and returns s1.

strncpy pads s1 with '\0's if s2 has fewer than n characters.

If s2 contains n or more characters, a '\0' is not copied to s1.

For example, to replace "abc" in a string str with "xyz":

        char *p = strstr( str, "abc");
        if( p != NULL)
            strncpy( p, "xyz", 3);
Another way of describing strncpy is that it copies exactly n characters into s1, using 0's if s2 contains less than n characters.

strncpy is not a direct safe replacement for strcpy.

For example, to prevent this buffer write overflow:

  char b[10], s[100];
  ... /* now suppose strlen(s) is 50 */
  strcpy( b, s); /* overflows b */
we can't just replace strcpy with strncpy:
  strncpy( b, s, 10); /* can not overflow b */
because now b does not contain a terminating zero byte, so string access to b will go past the end of the array, i.e. a buffer read overflow.

The correct way to use strncpy in this case is:

  strncpy( b, s, 10); /* can not overflow b */
  b[9] = 0; /* terminate b */