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?)
'const' variable is stored on stack.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With