※ 引述《swli.bbs@bbs.ntu.edu.tw (我喜歡寫程式)》之銘言:
> 是的, 我的意思大體上就是這樣, 但沒有你說的放常數的區段.
> 藉此修正一個說法, char *str = "string"; 的 "string" 是不是在 heap 中,
> 我並沒有嚴格的去探究,主要的意思是它會被擺在一個安全可供存取的區段裡頭.
> 在char str[]="string"; 宣告中的str 常數, 並不需要放在常數區段或者任何
> 記憶體中, 它就只是個數字罷了. 這個數字或許你可以把它想像成一個標籤,
> 在編譯過程中, 只要用到這個常數, compiler 就會直接以這個值去計算記憶體
> 的參考位址.
> 當你直接採用 char str[] = "string"; 的方式宣告一個 local array 時
> 前面有網友也說了, compiler 的動作會類似 直接在 stack 中塞進 's',
> 't', 'r','i','n','g','\0x0', 並賦予 str 這個常數值為存放第一個字元
> 's' 的 memory address 值的常數意義.
其實只要 C code 裡面出現 "string" 這種 literal constant string,
那 's' 't' 'r' 'i' 'n' 'g' '\0' 這個 sequence 必會出現在 constant pool 中,
而當你寫 char str[] = "string"; 且 str 非 global variable 時,
compiler 並不會直接產生一群分別填入這些字元到 stack 上的 code,
而是產生 load 之類的指令將這些值從 constant pool 搬至 stack。
--
Name: Tseng, Ling-hua E-mail Address: uranus@it.muds.net
School: National Tsing Hua University Department: Computer Science
Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design
Researching: Undecided
Homepage: https://it.muds.net/~uranus
--
╔═══╗ ┼────────────────────────╮
║狂狷 ║ │* Origin:[ 狂 狷 年 少 ] whshs.cs.nccu.edu.tw ╰─╮
║ 年少║ ┼╮ < IP:140.119.164.252 > ╰─╮
╚╦═╦╝ ╰ * From:61-230-216-250.dynamic.hinet.net
─╨─╨─ KGBBS ─ ◎ 遨翔"BBS"的狂狷不馴;屬於年少的輕狂色彩 ◎