字符串文字的地址长度 [英] Address length of a string literal

查看:114
本文介绍了字符串文字的地址长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到在具有GCC的Linux系统上,字符串文字的地址似乎比其他变量小得多.例如,下面的代码生成下面显示的o/p.

I see that on Linux systems with GCC the address of string literals seems to be much smaller than for other variables. For instance the following code generates the o/p shown below it.

#include <stdio.h>

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

    printf("str1 = %p\n", (void *) str1);
    printf("str2 = %p\n", (void *) str2);
    printf("&str3 = %p\n", (void *) str3);
    printf("&str4 = %p\n", (void *) str4);

    return 0;
}

输出:

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

是否有恒定的地址空间可分开使用?

Is there a constant address space separate for such usage?

推荐答案

标准未指定字符串文字将驻留的位置,但很可能位于只读数据部分.例如,在使用objdump的Unix系统上,您可以像这样检查只读数据部分:

The standard does not specify where string literals will reside but most likely it would be in the read only data section. For example on a Unix system using objdump you can inspect the read only data section like this:

objdump -s -j .rodata a.out

,并使用实时示例,我们可以看到类似于以下内容的输出:

and using a Live Example we can see output similar to this:

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 C99 draft standard section 6.4.5 String literals paragraph 5 says:

[...]然后,使用多字节字符序列来初始化静态存储持续时间和长度足以容纳该序列的数组.[...]

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

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

which means the lifetime of the string literal is the lifetime of the program and paragraph 6 says:

未确定这些数组是否不同,只要它们的元素具有 适当的值.如果程序尝试修改这样的数组,则行为是 未定义.

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.

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

So we don't know if they are distinct, that is going to be an implementation choice but we do know that we can not modify them. Otherwise it does not specify how they should be stored.

这篇关于字符串文字的地址长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆