This question already has an answer here:
I have a simple code.
#define MY_STRING "String example"
char* string_return_function()
{
return MY_STRING;
}
The above code works but I am not sure how. I think the string_return_function() returns a local address, which would gets freed once the function exits.
String literals are allocated in static read-only memory, usually called
.rodata
(read-only data). They persist throughout the whole life-time of your program, so it is safe to return a pointer to one.Had you however copied the string literal into a temporary stack variable, the code would be unsafe and invoke undefined behavior:
No, that's not how it works.
String literals are stored in memory that persists for as long as the program runs, so the function just returns a pointer to the string constant.
There is no string creation/initialization happening at run-time, no characters are copied around. It's just returning a pointer, the function's machine code is likely just a couple of instructions.
For example, here's the (cleaned-up) x86 code I got from https://assembly.ynh.io/:
Where
.LC0
is simply a location holding the string. So, that's 2 instructions including the return from functin overhead/boilerplate. Pretty efficient. :)You're thinking of this:
This is bad code since it returns a local array. It doesn't matter that the array in question is initialized from the literal, that's not what's being returned.
Also, don't name your function starting with
str
, all such names are reserved; the C11 draft says:String literals result in an array of
char
with static storage duration.For example, the 1999 C standard, section 6.4.5, para 5 starts with
The static storage duration means that the array representing the string literal continues to exist after the function
string_return_function()
returns.