Why should you use strncpy instead of strcpy?

后端 未结 10 1050

Edit: I\'ve added the source for the example.

I came across this example:

char source[MAX] = \"123456789\";
char source1[MAX] = \"12         


        
10条回答
  •  温柔的废话
    2020-11-22 06:19

    The strncpy() function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a fixed sized array, and a nul-terminator was only used if the filename was shorter than the array.

    That's what's behind the two oddities of strncpy():

    • It doesn't put a nul-terminator on the destination if it is completely filled; and
    • It always completely fills the destination, with nuls if necessary.

    For a "safer strcpy()", you are better off using strncat() like so:

    if (dest_size > 0)
    {
        dest[0] = '\0';
        strncat(dest, source, dest_size - 1);
    }
    

    That will always nul-terminate the result, and won't copy more than necessary.

提交回复
热议问题