Search code examples
cmemoryscopestaticauto

Automatic memory allocation occurs at compile time or at run time in C?


If we talk about static memory allocation it is said to be allocated at compile time but actually compiler just handles this memory allocation and it is actually allocated at start of program only. For example the compiler may create a large data section in the compiled binary and when the program is loaded in memory, the address within the data segment of the program will be used as the location of the allocated memory.

If I talk about automatic memory allocation, it is allocated when the control enters a new scope. Now my doubt is whether in this case also compiler comes into picture and passes some virtual addresses into the compiled binary which later becomes the addresses of actual allocated memory during runtime or this memory is allocated only at run time without any role of compiler just like the way dynamic memory is allocated ?

What if I have some local variable like:

int a = 10;

Will it have a compile time allocation or run time allocation ?


Solution

  • Automatic allocation happens in run-time, though the nature of it is very system-specific. Automatic storage duration variables may end up in registers, on the stack or optimized away entirely.

    In case they do end up on the stack, the compiler creates a local scope offset to the function where the variable is allocated. That is, the variable might be referred to as SP + 8 or something similar, where SP is the stack pointer. Which in turn could hold any value when the function is entered - the compiler or machine code does not know or care about that, which is why stack overflows exist.

    You might find this useful: What gets allocated on the stack and the heap?.