Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in memory are string literals ? stack / heap? [duplicate]

Possible Duplicate:
C String literals: Where do they go?

As far as I know,

generally, pointer have to be allocated by malloc(), and will be allocated to heap, then unallocated by free();

and

non pointer(int,char,float,etc..) will be allocated automatically to stack, and unallocated as long as the function go to return

but, from following code :

#include <stdio.h>

int main()
{
char *a;

a = "tesaja";

return 0;
}

where will a allocated to ? stack or heap ?

like image 382
capede Avatar asked Feb 11 '11 15:02

capede


People also ask

Where are string literals stored in memory?

Strings are stored on the heap area in a separate memory location known as String Constant pool.

Are string literals stored in heap?

The stack will store the value of the int literal and references of String and Demo objects. The value of any object will be stored in the heap, and all the String literals go in the pool inside the heap: The variables created on the stack are deallocated as soon as the thread completes execution.

Are string literals allocated on the stack?

The string literal will be allocated in data segment. The pointer to it, a , will be allocated on the stack. Therefore, the exact answer to your question is: neither. Stack, data, bss and heap are all different regions of memory.

Where are the strings stored stack heap Both stack & heap queue?

In Java, strings are stored in the heap area.


2 Answers

The string literal will be allocated in data segment. The pointer to it, a, will be allocated on the stack.

Your code will eventually get transformed by the compiler into something like this:

#include <stdio.h>

const static char literal_constant_34562[7] = {'t', 'e', 's', 'a', 'j', 'a', '\0'};

int main()
{
    char *a;

    a = &literal_constant_34562[0];

    return 0;
}

Therefore, the exact answer to your question is: neither. Stack, data, bss and heap are all different regions of memory. Const static initialized variables will be in data.

like image 91
ulidtko Avatar answered Sep 18 '22 19:09

ulidtko


a itself (the pointer) is defined as a local variable (implicitly) using the auto storage class, so it's allocated on the stack (or whatever memory the implementation uses for stack-like allocation -- some machines, such as IBM mainframes and the first Crays, don't have a "stack" in the normal sense).

The string literal "tesaja" is allocated statically. Exactly where that will be depends on the implementation -- some put it with other data, and some put it in a read-only data segment. A few treat all data as read/write and all code as read-only. Since they want they string literal to be read-only, they put it in the code segment.

like image 32
Jerry Coffin Avatar answered Sep 21 '22 19:09

Jerry Coffin