Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 371
Alfred Zhong Avatar asked Sep 16 '11 04:09

Alfred Zhong


People also ask

Are constants stored on the stack or heap?

'const' variable is stored on stack.

Are strings stored in heap or stack C?

When strings are declared as character arrays, they are stored like other types of arrays in C. For example, if str[] is an auto variable then the string is stored in stack segment, if it's a global or static variable then stored in data segment, etc.

Are strings allocated on stack or heap?

Stack space contains specific values that are short-lived whereas Heap space used by Java Runtime to allocate memory to objects and JRE classes. In Java, strings are stored in the heap area.

Are function variables stored in stack or heap?

The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack.


2 Answers

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

like image 111
Mahesh Avatar answered Nov 15 '22 07:11

Mahesh


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

like image 42
Dietrich Epp Avatar answered Nov 15 '22 06:11

Dietrich Epp