1

As per my understanding there is four segment where memory gets allocated i.e.code,data,bss and heap. My question in which segment does a string literal gets allocated?

int main(){
    char *ptr = "abcd";
}

In the above program where the memory for string literal gets allocated. And where ptr gets allocated? in stack?

Vikalp Patel
  • 10,669
  • 6
  • 61
  • 96
  • The string literal `"abcd"` will be placed in `.rodata (read-only data)` section of ELF, whereas the pointer will be allocated in the `stack`. – Abhineet Jun 04 '14 at 10:08
  • Also reading here http://stackoverflow.com/q/24018573/694576 might help to get enlighted. – alk Jun 04 '14 at 10:08
  • @VikalpPatel please do not change the brace formatting. In C, it is quite usual to have braces on a new line. Changing this may end up confusing a new user. – metacubed Jun 04 '14 at 10:09
  • I checked with size command after compiling above program in my Linux fedora machine.But the size of data segment remains same as before.is it getting stored somewhere elese? – user3706320 Jun 04 '14 at 10:11
  • $ objdump -s should work. – Abhineet Jun 04 '14 at 10:11
  • check this too:: https://sourceware.org/binutils/docs/binutils/objdump.html – Abhineet Jun 04 '14 at 10:13
  • Quoting from the [Jerrys's answer](http://stackoverflow.com/a/2589974/2455888): *Depending on the system you're writing for, and the capabilities of the executable file format it uses, they may be stored along with the program code in the text segment, or they may have a separate segment for initialized data.* Also read this [comment](http://stackoverflow.com/questions/2589949/c-string-literals-where-do-they-go#comment17141580_2589974) there. – haccks Jun 04 '14 at 10:15
  • Thanks.so .rodata section belongs to data segment or it is a separate segment maintained by the compiler. – user3706320 Jun 04 '14 at 10:24

1 Answers1

0

The string itself will be in the "data" segment. The pointer is probably on the stack, for many implementations. But there's no guarantee about that, it might be allocated to a register. Or all of the code might be optimized out, since it has no side-effects.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • I checked with size command after compiling above program in my Linux fedora machine.But the size of data segment remains same as before.is it getting stored somewhere elese?may be as you said its compiler dependent. – user3706320 Jun 04 '14 at 10:13