LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: firemoth

请教字符串常量保存在什么地方

[复制链接]
发表于 2005-5-18 09:22:20 | 显示全部楼层
Post by herberteuler
There are some segments in the binary file created by assembler and linker. For example, there are data, text, and bss segments in the old UNIX a.out format. String literals you refered often resides in data segment in the binary file. When linking several relocatable files, they will be relocated into the new data segment. For more information, please refer to Computer Systems: A Programmer's Perspective by Randal E. Bryant and David R. O'Hallaron (http://csapp.cs.cmu.edu/).

看起来正是我想要的
不知道有没有电子书?
我去搜一下   
回复 支持 反对

使用道具 举报

发表于 2005-5-18 09:22:53 | 显示全部楼层
呵呵,编译器没什么标准吧?
优化更没有标准.
优化做的好,用的人自然会多
回复 支持 反对

使用道具 举报

发表于 2005-5-18 09:25:33 | 显示全部楼层
只找到前言的pdf
回复 支持 反对

使用道具 举报

发表于 2005-5-18 09:50:55 | 显示全部楼层
Post by rickxbx
呵呵,编译器没什么标准吧?
优化更没有标准.
优化做的好,用的人自然会多

我的意思是说c/c++没做这样的规定
如果程序设计中用这样的trick的话,可移植性就不好了
回复 支持 反对

使用道具 举报

发表于 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, 看看结果是什么.
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表