Frage

The following code points to the first character in a char array available in read-only memory. Is that right?:

const char * ptr = "String one";

Now when ptr starts to point at another memory location:

ptr = "String two";

What happens to the first char array? Is that memory location freed when the execution ends?

War es hilfreich?

Lösung

The standard only says that string literals have static storage duration, which means that the lifetime of the variable is until the program ends and it is initialized when the program starts. The relevant section in the C11 draft standard is 6.4.5 paragraph 6:

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

It could be in read only memory and probably is but that is implementation defined. It does not need to be freed, only memory that is dynamically allocated via malloc needs a subsequent call to free.

If I use this program:

int main()
{
    const char * ptr = "String one";

    return 0;   
}

and we build it with gcc and then use objdump:

objdump -s -j .rodata a.out

We will find that in this case it is indeed stored in the read only data section:

Contents of section .rodata:
  400580 01000200 53747269 6e67206f 6e6500    ....String one. 

You can run it yourself here

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top