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/:
string_return_function:
movl $.LC0, %eax
ret
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:
char * bad_code(void)
{
char response[] = MY_STRING;
return response;
}
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:
Function names that begin with str
, mem
, or wcs
and a lowercase
letter may be added to the declarations in the <string.h>
header.