c - 函数的局部字符串常量存储在哪个段中?

标签 c pointers memory-management

<分区>

假设我们有如下一段代码

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/

相关文章:

java - Apache Commons CSV 框架是否提供内存高效的增量/顺序模式来读取大文件?

c - waitpid 用法错误?

c 将函数指针赋值给变量

c++ - C++实现URL匹配

c - **ptr 和 &ptr 的区别

c - 为什么在 C 中的 char 指针之间传输字符串时我的程序会崩溃?

objective-c - 保留在 NSThread 中创建的对象

c - 如果在函数内部调用 free() ,它是否只在本地释放?

c - c中的输入/输出扫描集

c - 缓冲区为空! : Cannot allocate memory