Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy() return value

Tags:

c

function

strcpy

A lot of the functions from the standard C library, especially the ones for string manipulation, and most notably strcpy(), share the following prototype:

char *the_function (char *destination, ...) 

The return value of these functions is in fact the same as the provided destination. Why would you waste the return value for something redundant? It makes more sense for such a function to be void or return something useful.

My only guess as to why this is is that it's easier and more convenient to nest the function call in another expression, for example:

printf("%s\n", strcpy(dst, src)); 

Are there any other sensible reasons to justify this idiom?

like image 213
Blagovest Buyukliev Avatar asked Aug 24 '10 22:08

Blagovest Buyukliev


People also ask

Can strcpy return null?

strcpy doesn't have any way to check errors itself. Also, it's required to always return dest , so it can only return NULL if it already tried to write into a NULL pointer, so a hypothetical system that catches SIGSEGV in strcpy and returns NULL would be violating that contract.

What does strcpy return failed?

The strcpy() function shall return s1; no return value is reserved to indicate an error.

How does strcpy () work?

strcpy() — Copy Strings 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 strcpy str1 str2 function return?

Return value of strcpy() This function returns the pointer to the destination string or you can say that it returns the destination string str1.


1 Answers

as Evan pointed out, it is possible to do something like

char* s = strcpy(malloc(10), "test"); 

e.g. assign malloc()ed memory a value, without using helper variable.

(this example isn't the best one, it will crash on out of memory conditions, but the idea is obvious)

like image 50
nothrow Avatar answered Oct 07 '22 04:10

nothrow