Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Why does strcpy return its argument?

Tags:

c

libc

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?

like image 480
Jo So Avatar asked May 05 '13 15:05

Jo So


People also ask

What does strcpy return in C?

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.

What is the problem with strcpy?

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.

Does strcpy copy null terminator in C?

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.

What does strncpy return?

The strncpy() function returns a pointer to string1 .


3 Answers

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));
like image 67
Fred Foo Avatar answered Oct 27 '22 23:10

Fred Foo


So that you can do something like

char * str = strcpy(malloc(12), "MyNewString");
like image 34
user93353 Avatar answered Oct 28 '22 01:10

user93353


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.

like image 31
Daniel Avatar answered Oct 27 '22 23:10

Daniel