堆还是堆?当在C ++中的函数调用中使用常量字符串时 [英] Heap or Stack? When a constant string is refered in function call in C++

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

问题描述

考虑函数:

  char * func()
{
returnSome thing ;
}

是常量 string char 数组)某事存储在堆栈中作为函数调用的本地或堆?



我是 函数被多次调用,有多少副本有事在内存中? (和是堆还是堆栈?)

解决方案

字符串字面量某事是 const char * 因此,它们既不在堆上也不在栈上,而是在只读位置,这是一个实现细节。



维基百科


资料



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



Consider the function:

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

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.

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

解决方案

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

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

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