c++ - 堆还是栈?当在 C++ 中的函数调用中引用常量字符串时

标签 c++ function global-variables heap-memory stack-memory

考虑函数:

char *func()
{
    return "Some thing";
}

常量 string (char array) "Some thing" 是存储在堆栈中作为函数调用的局部变量还是全局变量堆?

猜测它在堆中。

如果多次调用该函数,内存中有多少份"Some thing"? (它是堆还是堆栈?)

最佳答案

字符串文字“Some thing”的类型为const char*。因此,它们既不在堆上也不在堆栈上,而是在一个只读位置,这是一个实现细节。

来自 Wikipedia

Data

The data area contains global and static variables used by the program that are initialized. This segment can be further classified into initialized read-only area and initialized read-write area. For instance the string defined by char s[] = "hello world" in C and a C statement like int debug=1 outside the "main" would be stored in initialized read-write area. And a C statement like const char* string = "hello world" makes the string literal "hello world" to be stored in initialized read-only area and the character pointer variable string in initialized read-write area. Ex: static int i = 10 will be stored in data segment and global int i = 10 will be stored in data segment

关于c++ - 堆还是栈?当在 C++ 中的函数调用中引用常量字符串时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7440185/

相关文章:

c++ - 错误: expect a ';' before curly bracket [closed]

c++ - QObject 重入和线程安全

c++ - C++/错误: no matching function for call to

arrays - 将函数的返回值分配给Golang中Struct数组中的元素

ruby - 全局列表变量在我的应用程序中可以吗,或者我应该使用替代方案吗?

c++ - 在头文件中声明全局常量对象

c - 全局变量是否比 C 中的局部变量快?

c++ - 如何将 PNM 文件连接成数组?

c++ - 将长 64 位十进制转换为二进制

function - 无法在 map 函数中捕获异常