I have the following test:
char* test1()
{
char* string = "test 1\n";
printf("In function: %s", string);
return string;
}
char* test2()
{
char* string[10];
strcpy(string, "test 2\n");
printf("In function: %s", string);
return string;
}
int main()
{
printf("After returned: %s", test1());
printf("After returned: %s", test2());
}
output:
In function: test 1
After returned: test 1
In function: test 2
After returned: (null)
It seems that in test2() string is printed correctly, but after it was returned it become null.
How to properly return a string constructed via strcpy() and what is the reason for this behaviour?
Thank you in advance
The function
test1returns a pointer to a string literalString literals have static storage duration. That is the string literal used in the function
test1stays alive after exiting the function.The function
test2does not make sense and invokes undefined behavior.
For starters, the function
strcpy()expects its first argument to have typechar *while the expressionstringused as the first argument has the typechar **after implicit conversion of the array designator to pointer to its first element. And the conversion specifier%sused in the call of the functionprintf()also expects an argument of the typechar *but is supplied an argument of the typechar **.And again the function return type is
char *while the function returns an expression of the typechar **as explained above.And using the returned pointer to the local array
stringwith automatic storage duration after exiting the function invokes undefined behavior because the array is not alive after exiting the function. So the returned pointer is invalid.