Why should you use strncpy instead of strcpy?

后端 未结 10 1048

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

    The strncpy() function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy() function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits

    Also for POSIX API functions like read() which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy().

    In your example code, index is actually not an index, but a count - it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated

提交回复
热议问题