Search code examples
cmemory-managementdynamic-memory-allocationstatic-memory-allocation

I'm little bit confused that whether automatic memory allocation takes place during run time or compile time


I know that the memory is allocated at compile time to auto variables like int a; and are stored in stack but in case of a variable array whose input is taken from the user, for eg

#include<stdio.h>
main()
{
 int n;
 printf("enter the size of array");
 scanf("%d",&n);
 int a[n];
 .......
}

the memory is allocated at run time. So my question is, is the automatic allocation is case dependent or not. THANKS


Solution

  • In your example, it is unclear where "a" is defined. So, I'll take a stab at answering this by making assumptions on that.

    1. If the array is declared as a global array, it resides in the bss segment, and memory is allocated as the segments are loaded into memory.
    2. If the array is on the stack, and the size of the array is known at compile-time, the stack pointer is moved to allocate space for the array. You can see this if you disassemble the code.
    3. If the array is on the stack, but space is allocated based on an argument to the function you have a VLA(variable length array). These are commonly converted to "alloca" calls by the compiler. In this case the stack pointer is just moved to allocated "n" bytes on the stack.
    4. If the array is on the heap, the allocations are performed by the heap allocator in use.