Search code examples
cpointersmemory-managementdynamic-memory-allocationstring-literals

Where is memory allocated for an immutable string in c?


I'm trying to understand where memory is allocated in c programs.

void func1(char e, int f, int g)
{
    int b = 4;
    char * s = "hello world";
    char * temp = (char *) malloc(15); 

}

As I understand it, there are three automatic variables allocated on the stack b,s, and temp. where the contents of b (4) is stored on the stack, and the pointers s and temp are stored on the stack, and the data for temp is stored in the heap, but where is the data for s stored? because the b,s, and temp will be gone when we leave the func1 call but the memory for the contents has been allocated permanently. My other questions is the stack pointer always shifted down by 4 like when pushing the functions arguments on, even in the case of a char which is one byte? would the stack look like this, even though e is only one byte?

30:// other stuff
26: g
22: f
18: e

http://www.firmcodes.com/wp-content/uploads/2014/08/memory.png isnt this the layout for a c program?


Solution

  • In standard C terminology there are four possible storage durations:

    • automatic (b)
    • static ("Hello world")
    • dynamic (space allocated by malloc(15))
    • thread

    The other stuff you ask about in your question are properties of particular compilers and platforms. Some setups have no stack and no heap, no data segment or .data or .bss section, and so on.

    Further reading: