堆还是堆栈?当在c+&#x2B中引用常数字符串时
考虑函数:
char *func()
{
return "Some thing";
}
是常数字符串
(char
array)“某些东西”
存储在函数调用中的本地或全局在堆中?
我猜测它在堆中。
如果该函数被多次调用,则存储器中有多少份“某些东西”
? (这是堆还是堆栈?)
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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
字符串文字“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
恒定字符串通常用程序代码放置,而程序代码既不是堆也不是堆栈(这是实现细节)。只有一个副本,每次函数返回时,都会返回相同的指针值(这是由标准保证的)。由于字符串在程序内存中,因此有可能将其从未加载到内存中,如果您运行了程序的两个副本,则它们将在RAM中共享相同的副本(这仅适用于仅读取字符串,其中包括c)中的字符串常数。
Constant strings are usually placed with program code, which is neither heap nor stack (this is an implementation detail). Only one copy will exist, each time the function returns it will return the same pointer value (this is guaranteed by the standard). Since the string is in program memory, it is possible that it will never be loaded into memory, and if you run two copies of the program then they will share the same copy in RAM (this only works for read-only strings, which includes string constants in C).
它都不在程序的静态部分中。类似于将字符串作为全局变量。翻译单元中只有一个字符串的副本。
Neither, its in the static section of the program. Similar to having the string as a global variable. There is only ever one copy of the string within the translation unit.
它既不是堆,也不是堆栈上,它是所谓的 init部分可执行图像(COFF)。将其加载到内存中,并包含字符串之类的东西。
Neither on the heap, nor on stack, it is part of the so-called init section in the executable image (COFF). This is loaded into memory and contains stuff like strings.