简体   繁体   中英

C: function returning pointer

I have a difficulty in a conceptual problem

consider this code:

char *myfunc()
{
char *temp = "string";
return temp;
}

int main()
{
char* ptr = myfunc();
} 

I can't understand why ptr points to "string" after the function call. myfunc() creates an address in the stack which has the value "string" and another address which has the address of "string". When the function ends, the memory it had in the stack is freed so it should return a pointer pointing to an address that does not contain "string" anymore.

The location of the temp variable is on the stack, but the location of the string literal (to which temp points) is not stored on the stack. All string literals have a lifetime of the full runtime of the program, and so pointers to a string literal can be passed around freely.

But you should really get in the habit of using const char * when pointing to string literals, as string literals can't be modified.


From ISO/IEC 9899:2011, §6.4.5/6:

The multibyte character sequence is then used to initialize an array of static storage duration

(Emphasis mine)

When the specification says "static storage duration" it means that the lifetime is the same as the execution of the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM