(Joe keane) writes:
> In article <>,
> Keith Thompson <kst-> wrote:
>>There's rarely *any* reason to use strncpy(). It's not a "safer"
>>version of strcpy(); it's a quite different function.
>
> It is a safer version of 'strcpy'. There is the issue of what to do if
> the full copy can't be done, but that's program logic and the library
> function can't read people's minds. Even if the program just calls
> 'abort', that's a huge improvement.
Did you not read my description of what strncpy actually does, or do you
disagree with it?
strncat is a "safer" version of strcat. It takes an extra argument
"n" that specifies the maximum number of characters to be copied. If
the source is longer than n characters, it appends just n characters.
It properly zero-terminates the destination in all cases.
strncpy *looks* like it should be to strcpy as strncat is to strcat,
but it isn't. If the source string is shorter than n characters,
it will pad the destination with multiple null characters, something
that strcpy never does. If the source string is longer than n
characters, it will leave the destination unterminated (i.e.,
not a string).
If it had been defined something like this:
char *better_strncpy(char *dest, const char *src, size_t n) {
dest[0] = '\0';
return strncat(dest, src, n);
}
then it would be reasonable to call it a "safer" version of strcpy.
(It's possible I have an off-by-one error in the above code;
I haven't taken the time to check.)
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"