开发者

Heap or Stack? When a constant string is referred in function call in C++

开发者 https://www.devze.com 2023-04-05 10:59 出处:网络
Consi开发者_如何学Goder 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 th

Consi开发者_如何学Goder 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号