<分区>
假设我们有如下一段代码
char * fun(){
//some code
return "FooBar";
}
字符串“FooBar”存储在哪里?在数据段还是在本地栈?如果它存储在堆栈中,指针引用不会变得无效,因为字符串对于函数来说是本地的吗?
<分区>
假设我们有如下一段代码
char * fun(){
//some code
return "FooBar";
}
字符串“FooBar”存储在哪里?在数据段还是在本地栈?如果它存储在堆栈中,指针引用不会变得无效,因为字符串对于函数来说是本地的吗?
最佳答案
它可能(尽管不一定)与所有其他字符串常量一起存储在只读部分中,"FooBar"
只是解析为该字符串的地址,类似(伪汇编语言):
.sect readonly
foobar ds 'FooBar', 0 ; constant strings
.sect code
fun: load retreg, &foobar ; load address of it
retn ; and just return
但是,由于该标准没有指定内容的存储位置,因此这完全取决于实现。该标准倾向于规定行为,而不是实现该行为的基本方法。
这种情况下的行为由 ISO C11 6.4.5 String literals
,第 6 节(我的斜体)规定:
The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.
根据 5.1.2 Execution Environments
,它是静态存储持续时间这一事实意味着它在程序的整个持续时间内都存在:
All objects with static storage duration shall be initialized (set to their initial values) before program startup.
和 6.2.4 Storage durations of objects
第 3 部分,讨论静态存储持续时间:
Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
关于c - 函数的局部字符串常量存储在哪个段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827343/