加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 字符串文字的地址长度

发布时间:2020-12-16 10:25:04 所属栏目:百科 来源:网络整理
导读:我看到在使用GCC的 Linux系统上,字符串文字的地址似乎比其他变量小得多.例如,以下代码生成下面显示的o / p. #include stdio.hint main(){ char *str1 = "Mesg 1"; char *str2 = "Mesg 2"; char str3[] = "Mesg 3"; char str4[] = "Mesg 4"; printf("str1 = %
我看到在使用GCC的 Linux系统上,字符串文字的地址似乎比其他变量小得多.例如,以下代码生成下面显示的o / p.

#include <stdio.h>

int main()
{
    char *str1 = "Mesg 1";
    char *str2 = "Mesg 2";
    char str3[] = "Mesg 3";
    char str4[] = "Mesg 4";

    printf("str1 = %pn",(void *) str1);
    printf("str2 = %pn",(void *) str2);
    printf("&str3 = %pn",(void *) str3);
    printf("&str4 = %pn",(void *) str4);

    return 0;
}

输出:

str1 = 0x400668
str2 = 0x40066f
&str3 = 0x7fffcc990b10
&str4 = 0x7fffcc990b00

这种用法是否有一个独立的地址空间?

解决方法

该标准没有指定字符串文字将驻留在何处,但很可能它将在只读数据部分中.例如,在使用objdump的Unix系统上,您可以像这样检查只读数据部分:

objdump -s -j .rodata a.out

并使用Live Example我们可以看到类似于此的输出:

Contents of section .rodata:
 400758 01000200 4d657367 20310073 74723120  ....Mesg 1.str1 
 400768 3d202570 0a004d65 73672032 00737472  = %p..Mesg 2.str
 400778 32203d20 25700a00 26737472 33203d20  2 = %p..&str3 = 
 400788 25700a00 26737472 34203d20 25700a00  %p..&str4 = %p..

C99标准草案第6.4.5节字符串文字第5段说:

[…] The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.[…]

这意味着字符串文字的生命周期是程序的生命周期,第6段说:

It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array,the behavior is
undefined.

所以我们不知道它们是否是不同的,这将是一个实现选择,但我们知道我们无法修改它们.否则它没有指定它们应该如何存储.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读