Why should you use strncpy instead of strcpy?

后端 未结 10 922

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:31

    the strncpy is a safer version of strcpy as a matter of fact you should never use strcpy because its potential buffer overflow vulnerability which makes you system vulnerable to all sort of attacks

    0 讨论(0)
  • 2020-11-22 06:33

    What you're looking for is the function strlcpy() which does terminate always the string with 0 and initializes the buffer. It also is able to detect overflows. Only problem, it's not (really) portable and is present only on some systems (BSD, Solaris). The problem with this function is that it opens another can of worms as can be seen by the discussions on http://en.wikipedia.org/wiki/Strlcpy

    My personal opinion is that it is vastly more useful than strncpy() and strcpy(). It has better performance and is a good companion to snprintf(). For platforms which do not have it, it is relatively easy to implement. (for the developement phase of a application I substitute these two function (snprintf() and strlcpy()) with a trapping version which aborts brutally the program on buffer overflows or truncations. This allows to catch quickly the worst offenders. Especially if you work on a codebase from someone else.

    EDIT: strlcpy() can be implemented easily:

    size_t strlcpy(char *dst, const char *src, size_t dstsize)
    {
      size_t len = strlen(src);
      if(dstsize) {
        size_t bl = (len < dstsize-1 ? len : dstsize-1);
        ((char*)memcpy(dst, src, bl))[bl] = 0;
      }
      return len;
    }
    
    0 讨论(0)
  • 2020-11-22 06:38

    strncpy fills the destination up with '\0' for the size of source, eventhough the size of the destination is smaller....

    manpage:

    If the length of src is less than n, strncpy() pads the remainder of dest with null bytes.

    and not only the remainder...also after this until n characters is reached. And thus you get an overflow... (see the man page implementation)

    0 讨论(0)
  • 2020-11-22 06:39

    While I know the intent behind strncpy, it is not really a good function. Avoid both. Raymond Chen explains.

    Personally, my conclusion is simply to avoid strncpy and all its friends if you are dealing with null-terminated strings. Despite the "str" in the name, these functions do not produce null-terminated strings. They convert a null-terminated string into a raw character buffer. Using them where a null-terminated string is expected as the second buffer is plain wrong. Not only do you fail to get proper null termination if the source is too long, but if the source is short you get unnecessary null padding.

    See also Why is strncpy insecure?

    0 讨论(0)
提交回复
热议问题