c++ - 堆栈上的 Const C 字符串?

标签 c++

#include <iostream>

int main() {
    const char* s = nullptr;
    {
        s = "inner";
    }
    std::cout << s << std::endl;
    return 0;
}

“内”存放在内存的什么地方?

Valgrind 没有提示。是否存储在数据段中?

谢谢。

最佳答案

根据C++标准

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

所以尽管你的程序中的字符串字面值被用在 main 的内部 block 中

{
    s = "inner";
}

它一直存在,直到程序执行完毕,进程的所有内存都将被释放。

通常字符串字面量放在只读数据段中。

关于c++ - 堆栈上的 Const C 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29627441/

相关文章:

c++ - 如何在 BackgroundSubtractorMOG2 中禁用阴影跟踪?

c++ - C++ 构造函数中的混淆

c++ - operator<< 不能使用其 friend 数组的 IT 成员

c++ - SSBO CPU 映射返回正确的数据,但到 GPU 上的 SSBO 的数据为 'different'

c++ - opencv_highgui242.dll opencv 问题

c++ - STL 并行搜索算法的保证

c++ - Bitdefender 在使用 CodeBlocks 编译 C++ 源代码时指责病毒

c++ - 显示非常大的数字,由 byte[] 表示

c++ - 如何捕获从 Windows 服务启动的 session 注销

c++ - 如何使用与错误报告无关的区域设置 strtod