Reputation: 861
I am confused as to how we are able to return strings from function.
char* someFunction()
{
return "Hello, World"
}
Shouldn't the above return statement throw "function returns address of local variable" and how is it different from the function:
char* newFunction()
{
char temp[] = "Hello, World";
return temp;
}
which in fact does give the warning mentioned above.
Upvotes: 3
Views: 251
Reputation: 145919
String literals have static storage duration. You can return a pointer to a string and then access the string, it is perfectly valid and defined behavior.
char* someFunction()
{
return "Hello, World"
}
In the below case, you are returning a pointer to a string with automatic storage duration. An object with automatic storage duration is destroyed after exiting the block where it is defined. So accessing it after the function returns is undefined behavior.
char* newFunction()
{
char temp[] = "Hello, World";
return temp;
}
Upvotes: 1
Reputation: 11906
In the first case, the string lives in constant readonly memory at a fixed address for all time. In the second case, the string is put locally on the stack, and so is temporary.
Upvotes: 5