以下代码指向只读内存中可用的char 数组 中的第一个字符。是这样吗?:
const char * ptr = "String one";
现在当 ptr
开始指向另一个内存位置时:
ptr = "String two";
第一个 char 数组 发生了什么?执行结束时是否释放该内存位置?
最佳答案
标准只说字符串字面量有静态存储期,也就是说变量的生命周期是到程序结束,程序启动时初始化。 C11 draft standard中的相关部分是 6.4.5
段 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
动态分配的内存需要随后调用 free
。
如果我使用这个程序:
int main()
{
const char * ptr = "String one";
return 0;
}
然后我们使用 gcc
构建它,然后使用 objdump
:
objdump -s -j .rodata a.out
我们会发现,在这种情况下它确实存储在只读数据部分:
Contents of section .rodata:
400580 01000200 53747269 6e67206f 6e6500 ....String one.
可以自己运行here
关于c - 指向 Const Char 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003537/