LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1768|回复: 14

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

[复制链接]
发表于 2005-5-17 12:05:51 | 显示全部楼层 |阅读模式
如有如下语句:

  1. char *str = "hello world";
复制代码


请问字符串"hello world"是保存在什么地方的?
我的想法是:该字符串的类型可能是static char const *,因为如果把上面的语句放到一个子函数里面,在main()函数中通过指针依然可以正确的访问到这个字符串。
      还有另外一种可能。也许字符串通过malloc()得到,这样也可能在main()函数中访问,但如果不把它用free()释放掉,会出现脏数据。
      请问各位的看法?
发表于 2005-5-17 12:19:28 | 显示全部楼层
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-17 12:31:24 | 显示全部楼层
谢谢回复。是我提的问题有误,让你误解我的意思了。我是想知道,字符串变量是怎么实现的。是通过malloc动态分内存,还是用形如static arr[] = "hello world" 的静态保存。
回复 支持 反对

使用道具 举报

发表于 2005-5-17 12:49:18 | 显示全部楼层
There are no string variables in C. All strings appear in a C source file are called string literals, which are constants, and stored in data segment.
回复 支持 反对

使用道具 举报

发表于 2005-5-17 12:58:22 | 显示全部楼层
agree herberteuler
回复 支持 反对

使用道具 举报

发表于 2005-5-17 22:39:11 | 显示全部楼层
有时间觉得编译器挺傻的,每出现一个字符串就要在数据段中分配一个空间。有没有什么优化的方法,只要字符串完全相同就使用同一块空间?
回复 支持 反对

使用道具 举报

发表于 2005-5-17 22:41:28 | 显示全部楼层
惊叹,真的有!

  1. #include <stdio.h>

  2. #define HELLO_WORLD     "Hello World!\n"

  3. int main(void)
  4. {
  5.     printf("%x\n", HELLO_WORLD);
  6.     printf("%x\n", HELLO_WORLD);
  7.     printf("%x\n", HELLO_WORLD);
  8. }

复制代码


运行结果:
804846c
804846c
804846c
!!!!
回复 支持 反对

使用道具 举报

发表于 2005-5-18 08:59:07 | 显示全部楼层
Post by Tetris
惊叹,真的有!

  1. #include <stdio.h>

  2. #define HELLO_WORLD     "Hello World!\n"

  3. int main(void)
  4. {
  5.     printf("%x\n", HELLO_WORLD);
  6.     printf("%x\n", HELLO_WORLD);
  7.     printf("%x\n", HELLO_WORLD);
  8. }

复制代码


运行结果:
804846c
804846c
804846c
!!!!


这只是巧合,换一种编译器就不一定是这样了。
回复 支持 反对

使用道具 举报

发表于 2005-5-18 09:11:00 | 显示全部楼层
呵呵,这不是巧合,而是一个好的编译器应该做的优化工作.
回复 支持 反对

使用道具 举报

发表于 2005-5-18 09:17:46 | 显示全部楼层
但这不是标准
回复 支持 反对

使用道具 举报

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

本版积分规则

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