求解一个简单的 C 语言的问题, 事实证明我一直是错的

2020-08-25 14:18:16 +08:00
 Vibra

直接上代码

#include <stdio.h>

char *test() {
//    char res[] = "hello, world";
//    return res;
    return "hello, world";
}

const char *tt() {
    const char *str = test();
    printf("%s\n", str);
    return str;
}

int main() {
    const char *str = tt();
    printf("%s\n", str);
}

结果是打印了两次 hello world, 注释是两个乱码
所以, 请问 return “hello, world” 的这个存储 hello, world 的内存在什么地方

1932 次点击
所在节点    程序员
7 条回复
codehz
2020-08-25 14:23:59 +08:00
字符串常量区啊
Vibra
2020-08-25 14:26:50 +08:00
@codehz 了解了, 之前一直不知道还有这么一个区, 感谢
junnplus
2020-08-25 14:32:48 +08:00
你给 char res 加一个 static 就可以了,放在静态区
CismonX
2020-08-25 14:33:57 +08:00
字符串字面量一般存储在 .rodata 区段,而用字符串字面量来初始化字符数组时,则会将其拷贝到栈,当然函数返回后栈帧被释放,所以你注释掉的那个返回值其实是一个 dangling pointer
Vibra
2020-08-25 14:45:32 +08:00
@junnplus 我不知道的是还有字符串常量区, 这样可以不用加 static
akatquas
2020-08-25 17:57:05 +08:00
你找个编译成汇编的工具,一目了然。

常量字符串在 c 里面是有优化存储的。
甚至你`"%s\n"`这字符串也可以被存到了这个地方,取决于编译器行为。
推荐一个网站,https://godbolt.org/
Vibra
2020-08-26 16:58:21 +08:00
@akatquas 很有用, 感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/701272

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX