堆或堆栈?在C ++的函数调用中引用常量字符串时 [英] Heap or Stack? When a constant string is referred in function call in C++

查看:233
本文介绍了堆或堆栈?在C ++的函数调用中引用常量字符串时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Consider the function:

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

常量字符串 char array)Some thing作为函数调用的本地存储在堆栈中,或作为全局heap?

Is the constant string (char array) "Some thing" stored in the stack as local to the function call or as global in the heap?

我正在猜测它在堆中。

I'm guessing it's in the heap.

如果函数被多次调用,Some thing在内存中有多少个副本? (这是堆还是堆栈?)

If the function is called multiple times, how many copies of "Some thing" are in the memory? (And is it the heap or stack?)

推荐答案

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

String literal "Some thing" is of type const char*. So, they are neither on heap nor on stack but on a read only location which is a implementation detail.

From Wikipedia

From Wikipedia


数据

Data

数据区包含已初始化的程序
使用的全局变量和静态变量。该段可以进一步分为
初始化只读区和初始化读写区。对于
实例,C语言中由char s [] =hello world定义的字符串以及像int之外的int debug = 1的C
语句将存储在
中。写区域。并且像const char * string
=hello world这样的C语句使得字符串字面值hello world被存储在
初始化的只读区和字符指针变量字符串
中初始化读写区域。例如:static int i = 10将被存储在数据段中的
,并且全局int i = 10将被存储在数据段中

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 ++的函数调用中引用常量字符串时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆