In the virtual memory concept, where does C compilers store immediate strings? Example:
char *str = "Immediate string";
gcc
at least handles the following four cases differently:
char *globalstr = "immediate global string";
char globalbuf[] = "immediate global array of chars";
int main(int argc, char* argv[]) {
char *str = "immediate string";
char buf[] = "immediate array of chars";
return 0;
}
Local variable char *str
and global variable char *str
are stored into the .rodata
section:
$ readelf --hex-dump=.rodata foo
Hex dump of section '.rodata':
0x00400688 01000200 696d6d65 64696174 6520676c ....immediate gl
0x00400698 6f62616c 20737472 696e6700 696d6d65 obal string.imme
0x004006a8 64696174 65207374 72696e67 00 diate string.
The storage for local variable char buf[]
is allocated on the stack at runtime, and initialized via instructions in the .text
section:
$ readelf --hex-dump=.text foo
Hex dump of section '.text':
...
0x00400510 00000048 85c07408 bf480e60 00c9ffe0 ...H..t..H.`....
0x00400520 c9c39090 554889e5 4883ec50 897dbc48 ....UH..H..P.}.H
0x00400530 8975b064 488b0425 28000000 488945f8 .u.dH..%(...H.E.
0x00400540 31c048c7 45c8a406 4000c745 d0696d6d [email protected]
0x00400550 65c745d4 64696174 c745d865 206172c7 e.E.diat.E.e ar.
0x00400560 45dc7261 7920c745 e06f6620 63c745e4 E.ray .E.of c.E.
0x00400570 68617273 c645e800 b8000000 00488b55 hars.E.......H.U
0x00400580 f8644833 14252800 00007405 e897feff .dH3.%(...t.....
...
The global variable char buf[]
is stored in the .data
section:
$ readelf --hex-dump=.data foo
Hex dump of section '.data':
0x00601020 00000000 00000000 00000000 00000000 ................
0x00601030 00000000 00000000 00000000 00000000 ................
0x00601040 8c064000 00000000 00000000 00000000 ..@.............
0x00601050 00000000 00000000 00000000 00000000 ................
0x00601060 696d6d65 64696174 6520676c 6f62616c immediate global
0x00601070 20617272 6179206f 66206368 61727300 array of chars.
The compiler most likely stores string literals in .text
. When the program is executed .text
is usually paged in a read-only page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With