I have come across two popular ways to write a safe copy function that is portable and conforms to C89.
Example 1:
strncpy(dst, src, size);
dst[size - 1] = '\0';
Example 2:
dst[0] = '\0'
strncat(dst, src, size - 1);
Do these approaches provide the exact same result, or would there be any differences in dst
contents between one example and the other?
Yes, they are technically different. Though you may not care about the trivial difference.
e.g. if you initialize like this:
char dst[] = "abcdefg";
char src[] = "12";
size_t size = sizeof dst;
Then with your "Example 1", dst
becomes 0x31 0x32 0x00 0x00 0x00 0x00 0x00 0x00
With your "Example 2", dst
becomes 0x31 0x32 0x00 0x64 0x65 0x66 0x67 0x00
If you only want to copy the string, then the difference doesn't matter.
It's hard to say which one is better. But in the case of a very big size
and a very short src
, setting all the trailing null characters with the "Example 1" approach might make the program a bit slower.