Why should you use strncpy instead of strcpy?

后端 未结 10 1052

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 combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing \0, which may not always occur.

    Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n characters, where n is the third argument.

    The n functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy.

提交回复
热议问题