【发布时间】:2020-08-01 23:20:54
【问题描述】:
C语言中const char*和static const char*有什么区别?
我认为Difference between static const char* and const char*的答案是错误的。
确实,const char* 元素放在程序的.rodata 部分,否则会导致段错误:
const char* f() {
const char* hello = "hello";
return hello;
}
int main() {
const char* hello_after = f();
printf("%s\n", hello_after);
}
确实,由于该代码有效,f 返回的指针仍然指向活动数据,这表明该数据不是在堆栈上分配,而是存储在.rodata 中。
但是,在我看来,就 GCC 而言,const char* 和 static const char* 是相同的东西。
但是,为什么 const int* 和 static const int* 的行为不一样?这是一个例外,在 GCC 中硬编码,仅适用于 char 类型,然后 const 和 static const 应该相同?
非常感谢您的帮助!
【问题讨论】:
-
这与
const char*的关系较小,而与字符串文字(在这种情况下为"hello")的关系更大 -
我认为您误解了链接的答案。他们讨论了指针的存储位置——而不是字符串文字。根据
static的使用,指针的存储方式会有所不同@ -
如果你用
-fsanitize=address编译你会得到一个运行时错误(godbolt.org/z/37rH-L) -
引用:“确实,const char* 元素被放在程序的 .rodata 部分......” 错误 - 字符串文字是但不是指针。
标签: c memory static string-literals