1

Suppose we have the following piece of code

char * fun(){
    //some code
    return "FooBar";
}

Where is the string "FooBar" store? In the data segment or in the local stack? If it is stored in the stack, would the pointer reference not become invalid since the string would be local to the function?

kauray
  • 739
  • 2
  • 12
  • 28

2 Answers2

4

It's probably (though not necessarily) stored in a read-only section along with all other string constants, and "FooBar" simply resolves to the address of that string, something like (pseudo assembly language):

.sect readonly
    foobar  ds 'FooBar', 0             ; constant strings
.sect code
    fun:    load retreg, &foobar       ; load address of it
            retn                       ; and just return

However, since the standard specifies nothing about where things are stored, this is totally down to the implementation. The standard tends to dictate behaviour rather than underlying methods to implement that behaviour.

The behaviour in this case is dictated by ISO C11 6.4.5 String literals, section 6 (my italics):

The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.

The fact that it is static storage durations means that it exists for the entire duration of the program, as per 5.1.2 Execution Environments:

All objects with static storage duration shall be initialized (set to their initial values) before program startup.

and 6.2.4 Storage durations of objects in section 3, discussing static storage duration:

Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

The C language standard doesn't use terms like "segment" or "stack". These terms are used by some implementations.

A string literal represents an array of static storage duration, which means it lives during the entire execution of the program and is not confined to any block or function.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243