Just curious to know (as we use these functions often). I don\'t see any practical difference between strncpy() and memcpy(). Isn\'t it worth to say that effectively,
No, they are not the same.
From the C Standard (ISO/IEC 9899:1999 (E))
7.21.2.3 The strcpy function
Description
2 The strncpy function copies not more than n characters (characters that follow a null character are not copied) from the array pointed to by s2 to the array pointed to by s1.260) If copying takes place between objects that overlap, the behavior is undefined.
3 If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.
Returns
4 The strncpy function returns the value of s1.
7.21.2.1 The memcpy function
Description
2 The memcpy function copies n characters from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
Returns 3 The memcpy function returns the value of s1.
when using memcpy()
the source and destination buffers can overlap, while in strncpy()
this must not happen.
According to the C standard, the behavior for overlapping buffers are undefined for both strncpy()
and memcpy()
.
According to the C standard, the real difference between strncpy()
and memcpy()
is that if the source string is less then N value, then NULL characters are appended to the remaining N quantity.
memcpy()
is more efficient, but less safe, since it doesn't check the source to see if it has N quantity to move to the target buffer.