你是对的,第一种情况的“hello”是 mutable 而第二种情况是 immutable 字符串。它们在初始化之前保存在只读存储器中。
在第一种情况下,可变内存是从不可变字符串初始化/复制。在第二种情况下,指针指向不可变字符串。
对于第一种情况,维基百科说,
这些变量的值最初存储在
只读存储器(通常在 .text 中)并被复制到
程序启动过程中的.data段。
让我们检查 segment.c 文件。
char*s = "hello"; // string
char sar[] = "hello"; // string array
char content[32];
int main(int argc, char*argv[]) {
char psar[] = "parhello"; // local/private string array
char*ps = "phello"; // private string
content[0] = 1;
sar[3] = 1; // OK
// sar++; // not allowed
// s[2] = 1; // segmentation fault
s = sar;
s[2] = 1; // OK
psar[3] = 1; // OK
// ps[2] = 1; // segmentation fault
ps = psar;
ps[2] = 1; // OK
return 0;
}
这是为segment.c 文件生成的程序集。请注意,s 和 sar 都在 global aka .data 段中。似乎 sar 是 const pointer 到一个 mutable initialized 内存或根本不是指针(实际上它是一个数组)。最终它暗示sizeof(sar) = 6 与sizeof(s) = 8 不同。 readonly(.rodata) 部分中有“hello”和“phello”,实际上是不可变。
.file "segment.c"
.globl s
.section .rodata
.LC0:
.string "hello"
.data
.align 8
.type s, @object
.size s, 8
s:
.quad .LC0
.globl sar
.type sar, @object
.size sar, 6
sar:
.string "hello"
.comm content,32,32
.section .rodata
.LC1:
.string "phello"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $64, %rsp
movl %edi, -52(%rbp)
movq %rsi, -64(%rbp)
movq %fs:40, %rax
movq %rax, -8(%rbp)
xorl %eax, %eax
movl $1752326512, -32(%rbp)
movl $1869376613, -28(%rbp)
movb $0, -24(%rbp)
movq $.LC1, -40(%rbp)
movb $1, content(%rip)
movb $1, sar+3(%rip)
movq $sar, s(%rip)
movq s(%rip), %rax
addq $2, %rax
movb $1, (%rax)
movb $1, -29(%rbp)
leaq -32(%rbp), %rax
movq %rax, -40(%rbp)
movq -40(%rbp), %rax
addq $2, %rax
movb $1, (%rax)
movl $0, %eax
movq -8(%rbp), %rdx
xorq %fs:40, %rdx
je .L2
call __stack_chk_fail
.L2:
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
同样对于 main 中的 local 变量,编译器不会费心创建 name。它可能会将其保存在 register 或 stack 内存中。
请注意,局部变量值“parhello”已优化为 1752326512 和 1869376613 数字。我通过将“parhello”的值更改为“parhellp”来发现它。汇编输出的diff如下,
39c39
< movl $1886153829, -28(%rbp)
---
> movl $1869376613, -28(%rbp)
所以 psar 没有单独的不可变存储。它在代码段中变成整数。