Search code examples
c++functionglobal-variablesheap-memorystack-memory

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


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?)


Solution

  • 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