Why string copied by strcpy() after returning from function is null in C

86 Views Asked by At

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

2

There are 2 best solutions below

2
Vlad from Moscow On BEST ANSWER

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 invokes undefined behavior.

For starters, the function strcpy() expects its first argument to have type char * while the expression string used as the first argument has the type char ** after implicit conversion of the array designator to pointer to its first element. And the conversion specifier %s used in the call of the function printf() also expects an argument of the type char * but 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.

0
Aevo On

It's because the first piece of code uses a pointer to return a value, which stays intact after the function finishes executing, and can still be accessed after function 1 has finished executing, however, the second piece of code tries to return a value but when it finishes executing, it cannot return that value because the string does not exist in memory anymore (for function 2) since it is a character array and not pointer, hence why you get null. Also in function 2, character arrays are defined as char arr[] = "";. There is no requirement for the * there, else it gets treated as a pointer to an array of type char and not a character array.