Possible Duplicate:
Is returning a string literal address from a function safe and portable?
“life-time” of string literal in C
Hello i am confused somewhat
char *func()
{
return "Hello";
}
Here "Hello" is sequence/array of characters. It is a local variable and it must vanish away as soon as the function returns. Then how come we are able to get the correct value?
The "Hello"
is a string literal and will exist for the lifetime of the program. To quote the relevant sections of the C99 standard:
...The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence...
An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
The return value of the function should be const char*
as an attempt to modify a string literal is undefined behaviour.