J
jake1138
CBFalconer said:Richard said:CBFalconer said:jake1138 wrote:
Wouldn't a function like this give you safety and NUL-termination?
char *mystrncpy(char *dest, const char *src, size_t size)
{
*dest = '\0';
return strncat(dest, src, size-1);
}
no. Think about it.
Ok, I've thought about it. Given
char s1[20];
char s2[]="abcdefghijklmnopqrstuvwxyz";
how is
mystrcpy(s1, s2, 20);
less safe than
strlcpy(s1, s2, 20);
mystrcpy leaves an unterminated string (no '\0') in s1, and returns
a pointer to s1, which will almost certainly lead to future
faults. strlcpy leaves a terminated string in s1, and returns 26
to indicate the size required. Since 26 >= 20 you know the output
was truncated.
I don't see how mystrncpy (it has an 'n' in it) will leave an
unterminated string. s1[0] is immediately set to '\0', then strncat
will write over that up to size-1 length then add a '\0' on the end.
I've tested this and it seems to work as expected. Please explain.