指针为const char [英] Pointers To Const Char

查看:182
本文介绍了指针为const char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code点的第一个字符中的字符数组的只读内存可用。是这样吗?

The following code points to the first character in a char array available in read-only memory. Is that right?:

const char * ptr = "String one";

现在,当 PTR 开始在其他内存位置指向:

Now when ptr starts to point at another memory location:

ptr = "String two";

发生了第一次的字符数组的是什么?当执行结束是内存位置中解脱出来?

What happens to the first char array? Is that memory location freed when the execution ends?

推荐答案

该标准只说字符串具有的静态存储持续时间的,这意味着变量的生存期是直到程序结束,在程序启动时它被初始化。在 C11标准草稿的相关部分 6.4.5 段的 6 :​​

The standard only says that string literals have static storage duration, which means that the lifetime of the variable is until the program ends and it is initialized when the program starts. The relevant section in the C11 draft standard is 6.4.5 paragraph 6:

...]的多字节字符序列然后用于初始化静态存储持续时间和长度刚好足以包含序列的阵列。 [...]

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

有可能是在只读存储器和可能是,但是实现定义。它并不需要被释放,只有通过的malloc 动态分配的内存需要的后续调用免费

It could be in read only memory and probably is but that is implementation defined. It does not need to be freed, only memory that is dynamically allocated via malloc needs a subsequent call to free.

如果我使用这个程序:

int main()
{
    const char * ptr = "String one";

    return 0;   
}

和我们与 GCC ,然后用它建立 objdump的

and we build it with gcc and then use objdump:

objdump -s -j .rodata a.out

我们会发现,在这种情况下,它确实是存储在只读数据部分:

We will find that in this case it is indeed stored in the read only data section:

Contents of section .rodata:
  400580 01000200 53747269 6e67206f 6e6500    ....String one. 

您可以自己<一个运行href=\"http://coliru.stacked-crooked.com/view?id=6895540947d56af9dab606064fa9209a-f37ccd9fde735da9113f829339b56ada\"相对=nofollow>这里

这篇关于指针为const char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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