gpt4 book ai didi

c - 为什么声明到 main 函数中的局部字符串是 Rodata 段内存的一部分?

转载 作者:行者123 更新时间:2023-12-05 02:20:16 25 4
gpt4 key购买 nike

反汇编后的代码如下:

#include <stdio.h>

static const char HELLO1[] = "Howdy";

int main(){
char hello2[6]="hello\0";
printf("%s",string);
}

我可以看到字符串 HELLO1 被声明到 .RODATA 段中,这是可以理解的,因为常量变量被声明到该段中。

但是,hello2 也被声明到 .RODATA 段中。但是局部变量是直接在Stack中声明的吧?

你能解释一下为什么这个字符串被声明到这个段中吗?

最佳答案

String literals在程序的生命周期内存在

String literals have static storage duration, and thus exist in memory for the life of the program.

Static storage duration .

The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern.

于是gccELF二进制文件中.RODATA中实现了静态存储

进一步阐述...

char a[] = "Hello world A";
char* p = "Hello world P";

对于ap,它们的字符串字面量都具有静态存储持续时间(这意味着它们都存储在.RODATA中),但有所不同因为对于 a,字符串文字被复制到这个堆栈变量中,而 p 只是指向 .RODATA 内存。这就是为什么你可以修改 a 但不能修改 p

注意:知道上面的引用来自 c++ 语法,但是 c 的原因是相同的

关于c - 为什么声明到 main 函数中的局部字符串是 Rodata 段内存的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39820406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com