12

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?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
2013Asker
  • 2,008
  • 3
  • 25
  • 36
  • 2
    String literals are static allocations. They do not need to be freed. – Fred Larson Aug 01 '13 at 20:08
  • Check this question too: [Should I free char* initialized using string-literals?](http://stackoverflow.com/questions/9504588/should-i-free-char-initialized-using-string-literals) – sidyll Aug 01 '13 at 20:11
  • 1
    Why should it be freed ? the pointer just points to a different string literal and as explained in the accepted answer the string literals have static storage duration so they ain't freed . – 0decimal0 Aug 02 '13 at 03:43

1 Answers1

7

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

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • So it will be automatically deleted from memory when the program is closed? – 2013Asker Aug 01 '13 at 20:14
  • @2013Asker Yes, when your program exits it will release it resources to the system. – Shafik Yaghmour Aug 01 '13 at 20:18
  • 4
    On a typical hosted implementation, a string literal will probably be in memory that's marked as read-only by the operating system, not in physical ROM, and all your program's memory will almost certainly be released when the program finishes. On a freestanding implementation, it could be a different story; a very low-level system might run just one program, whose code and static data are stored in ROM that's never erased. – Keith Thompson Aug 01 '13 at 20:20