Edit: I\'ve added the source for the example.
I came across this example:
char source[MAX] = \"123456789\";
char source1[MAX] = \"12
The strncpy()
function was designed with a very particular problem in mind: manipulating strings stored in the manner of original UNIX directory entries. These used a fixed sized array, and a nul-terminator was only used if the filename was shorter than the array.
That's what's behind the two oddities of strncpy()
:
For a "safer strcpy()
", you are better off using strncat()
like so:
if (dest_size > 0)
{
dest[0] = '\0';
strncat(dest, source, dest_size - 1);
}
That will always nul-terminate the result, and won't copy more than necessary.