|
|
发表于 2005-5-21 00:37:56
|
显示全部楼层
以下是gcc的实现, 其他c编译器我没有做过验证,
int main()
{
char *s = "hello";
strcpy(s, "shit");
printf("hello");
return 0;
}
编译后运行一定会Segmentation fault,
可以看看汇编代码, gcc -S -o test.s test.c
.file "test.c"
.section .rodata
.LC0:
.string "hello"
.LC1:
.string "shit"
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
subl $24, %esp
andl $-16, %esp
movl $0, %eax
subl %eax, %esp
movl $.LC0, -4(%ebp)
movl $.LC1, 4(%esp)
movl -4(%ebp), %eax
movl %eax, (%esp)
call strcpy
movl $.LC0, (%esp)
call printf
movl $0, %eax
leave
ret
.size main, .-main
.section .note.GNU-stack,"",@progbits
.ident "GCC: (GNU) 3.3.6 (Debian 1:3.3.6-5)"
看到第二行了吗, .section .rodata , 字符串常量是被放在rodata segmentation中的
也就是代码区, 是只读的, 这样做是为了实现常量这个概念的, 你一定不会想printf("hello");
打印出来的会是"shit"吧, 可以试试将 .section .rodata改成 .section .data, 然后再编
译一下 gcc -o test test.s, 看看结果是什么. |
|