strncpy not intended to be used as a more secure strcpy , it should be used to insert one line in the middle of another.
All of these "safe" string handling functions, such as snprintf and vsnprintf , are patches that have been added to later standards to mitigate buffer overflow exploits, etc.
Wikipedia mentions strncat as an alternative to writing its own secure strncpy :
*dst = '\0'; strncat(dst, src, LEN);
EDIT
I missed that strncat exceeds LEN characters when null terminates a string if it is longer or equal to LEN char.
In any case, the point of using strncat instead of any homegrown solution like memcpy (..., strlen (...)) / regardless of the fact that the strncat implementation can be optimized for the target / platform in the library.
Of course, you need to verify that dst contains at least nullchar, so using strncat correctly would be something like:
if(LEN) { *dst = '\0'; strncat(dst, src, LEN-1); }
I also assume that strncpy is not very useful for copying a substring to another string, if src is shorter than n char, the destination string will be truncated.
Ernelli Sep 21 '09 at 11:12 2009-09-21 11:12
source share