内存会话用于存储直接字符串,在C中

时间:2011-05-31 08:59:35

标签: c string virtual-memory

在虚拟内存概念中,C编译器在哪里存储直接字符串?例如:

char *str = "Immediate string";

2 个答案:

答案 0 :(得分:6)

gcc至少以不同方式处理以下四种情况:

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;
}

本地变量char *str和全局变量char *str存储在.rodata部分中:

$ 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.

本地变量char buf[]的存储在运行时分配在堆栈上,并通过.text部分中的说明进行初始化:

$ 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 1.H.E...@..E.imm
  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.....
...

全局变量char buf[]存储在.data部分:

$ 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.

答案 1 :(得分:2)

编译器很可能在.text中存储字符串文字。执行程序时.text通常在只读页面中进行分页。