Why should you use strncpy instead of strcpy?

后端 未结 10 1054

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

    strncpy is NOT safer than strcpy, it just trades one type of bugs with another. In C, when handling C strings, you need to know the size of your buffers, there is no way around it. strncpy was justified for the directory thing mentioned by others, but otherwise, you should never use it:

    • if you know the length of your string and buffer, why using strncpy ? It is a waste of computing power at best (adding useless 0)
    • if you don't know the lengths, then you risk silently truncating your strings, which is not much better than a buffer overflow

提交回复
热议问题