1

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.

2
  • 1
    Where did you learn that "myfunc() creates an address in the stack"? Commented Nov 18, 2015 at 17:24
  • 1
    Since temp is a string literal, it is pointing to the ROM segment, which is usually in the Data section of memory, not on the stack. Commented Nov 18, 2015 at 17:26

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

12 Comments

Are you sure a pointer to string literal can be returned from a function? temp is automatic local variable.
@haccks Yes, the location of string literals are static through the runtime of the program. Their address won't change. Returning a pointer to temp (e.g. &temp) will however lead to UB since that variable will "disappear" when the function returns.
I think I am missing something here. It would be nice if you can quote some reference from standard.
@haccks Remember that in C values are passed and returned by value, which means the value is copied. Returning a pointer means that the pointer is passed/returned by value, i.e. the pointer is copied.
It is perhaps significant here that pointers are not arrays. It matters in this case because the the OP's code would not be correct if temp were instead declared char temp[] = "string";.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.