Why does strcpy(3)
(and strncpy(3)
) return their first argument? I don't see how this does add any value. Instead, frequently I'd rather have the number of copied bytes returned.
Addendum: What am I supposed to do when I need also the length of the resulting string? Do I really have to implement my own version?
In the C Programming Language, the strcpy function copies the string pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination.
Problem with strcpy(): The strcpy() function does not specify the size of the destination array, so buffer overrun is often a risk. Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk.
The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.
The strncpy() function returns a pointer to string1 .
For historical reasons. strcpy
and friends date back to the early seventies, and I guess the intended use case for the return value would be a kind of chaining:
// copy src into buf1 and buf2 in a single expression
strcpy(buf1, strcpy(buf2, src));
Or
char *temp = xmalloc(strlen(const_str) + 1);
function_that_takes_mutable_str(strcpy(temp, const_str));
So that you can do something like
char * str = strcpy(malloc(12), "MyNewString");
Most of the string functions in the C library have been designed by amateurs. For instance, in my 25 years of my career, I never used the strcat() function, yet I concatenate strings all the time. Also, if you think the printf(), there is little documentation if you pass NULL for a %s argument. The same goes for for the %c passing a '\0', or a malloc(0).
Sadly, the most useful strcpy() should return a pointer to the end of the destination buffer to chain copying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With