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
>Solution :
The function test1
returns a pointer to a string literal
char* test1()
{
char* string = "test 1\n";
printf("In function: %s", string);
return string;
}
String literals have static storage duration. That is the string literal used in the function test1
stays alive after exiting the function.
The function test2
char* test2()
{
char* string[10];
strcpy(string, "test 2\n");
printf("In function: %s", string);
return string;
}
does not make sense and invoke undefined behavior.
For starters the function strcpy
expects the first argument of the type char *
while the expression string
used as the first argument has the type char **
after implicit conversion the array designator to pointer to its first element. Also the conversion specifier s
ysed in the call of the function printf
also expects an argument of the type char *
but there is supplied an argument of the type char **
..
And again the function return type is char *
while the function returns an expression of the type char **
as explained above.
And using the returned pointer to the local array string
with 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.