When is memory allocated for a variable in c?
When is memory allocated for a variable in c? Does this happen during declaration or initialization? Does it differ in volume or storage class?
For example:
int i; <<<<<<<< memory gets allocated here? i=10; <<<<<<<< memory gets allocated here?
I think it is allocated during the declaration itself. Correct me if I am wrong.
source to share
- Local function variables are allocated on the stack frame and initialized when the function is called.
- Arguments passed to functions are either on the stack or passed through registers. It depends on your calling convention.
- They can be heap allocated if you use
malloc
and friends. - Variables
static
are allocated in the data section if they have initialization (static int a=1;
) values , otherwise they will be implicitly zeroed out and allocated to the BSS (static int a;
) section . They are initialized before beingmain
called.
As for your specific example,
int i; i = 10;
the compiler will allocate i
on the stack the stack. It will probably set the value right away. So it will highlight and initialize it when you enter this area.
Take for example
#include <stdio.h>
int main()
{
int foo;
foo = 123;
printf("%d\n", foo);
}
Compile this with
gcc -O0 a.c -S
This creates an assembly file a.s
. If you check it, you can actually see it foo
copied right onto the stack frame:
movl $123, -4(%rbp)
or in Intel syntax (add -masm=intel
in gcc
):
mov DWORD PTR [rbp-4], 123
On the right below you will see call printf
.
RBP register refers to the stack frame, so this variable in this case only exists on the stack frame because it is only used when called printf
.
source to share
You can allocate memory:
- In one of the program data segments by the compiler. These segments are the part of the program loaded by the OS when the program is started (or called as needed). (Static variables)
- On the stack at runtime. (Stack / auto variables)
- From the heap at runtime. (Via malloc () or something similar)
source to share
int bla = 12; // bla is allocated prior to program startup
int foo(void)
{
while (1)
{
/* ... code here ... */
int plop = 42; // plop is allocated at the entry of the while block
static int tada = 271828; // tada is allocated prior to program startup
}
int *p = malloc(sizeof *p); // object is allocated after malloc returns
}
source to share