6

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?

Jo So
  • 25,005
  • 6
  • 42
  • 59
  • 2
    So that it can be used in function chaining. – Alok Save May 05 '13 at 15:49
  • 1
    It would be far more useful if a variant of `strcpy()` returned a pointer to the `'\0'` byte at the end of the string. However, if you length check everything before you do your copying (as you should to be safe), you can use `memmove()` (or maybe `memcpy()`) instead of `strcpy()`. It's only when you don't have a length available that can't use those, but it is arguably not safe to do the copying if you don't know the lengths of the source string and the target buffer. – Jonathan Leffler May 05 '13 at 16:04
  • @JonathanLeffler re: _"It would be far more useful if a variant of strcpy() returned a pointer to the '\0' byte at the end of the string"_: There is (in POSIX). It's called [`stpcpy(3)`](https://man7.org/linux/man-pages/man3/stpcpy.3.html). – alx - recommends codidact Oct 18 '21 at 15:51
  • And, for chaining memcpy(3), there's GNU's `mempcpy(3)`.; the same with better return value – alx - recommends codidact Dec 09 '22 at 16:40

3 Answers3

4

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));
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Didn't they have comma expressions at the time? `function1((strcpy(buf1, const_str), buf1))`. – Jo So May 05 '13 at 15:56
  • 1
    @JoSo: I'm not sure when comma expressions were introduced, but I've read quite a lot of old C code and I don't think I ever saw it being used. I personally also never use it except in macros. – Fred Foo May 05 '13 at 16:33
1

So that you can do something like

char * str = strcpy(malloc(12), "MyNewString");
user93353
  • 13,733
  • 8
  • 60
  • 122
1

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.

Daniel
  • 51
  • 3