Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is memory allocated with a const char pointer? [duplicate]

Tags:

c++

c

memory

Possible Duplicate:
Is a string literal in c++ created in static memory?
C++ string literal data type storage

In this code:

const char * str = "hello world";

If I understand correctly a pointer is 4 or 8 bytes, which I guess would be allocated on the stack. But where is the memory for the "hello world" allocated and stored?
Or what does str point to exactly?

like image 373
Josh Avatar asked Jan 22 '13 21:01

Josh


3 Answers

It's not allocated. It's generally stored in your program's code segment or on the stack That's up to the compiler. Either way, it points to a null-terminated array of characters.

like image 176
paddy Avatar answered Oct 23 '22 08:10

paddy


C has no stack or heap. C says that "hello world" is a string literal and that string literals have static storage duration.

like image 20
ouah Avatar answered Oct 23 '22 08:10

ouah


Essentailly, that is compiled as if you had written:

const static char helloworld[12] 
             = {'h', 'e', 'l', 'l', 'o',' ','w', 'o', 'r', 'l', 'd', '\0'};

const char * str = helloworld;

The array would normally be placed in some read-only section of memory, probably near the executable code.

Depending on where it's defined, str will be in the stack or global memory space.

like image 38
James Curran Avatar answered Oct 23 '22 07:10

James Curran