When does memory gets allocated for a variable in c? Does it happen during declaration or initialization? Does this differ based on the scope or storage class?
Eg:
int i; <<<<<<<< memory gets allocated here?
i=10; <<<<<<<< memory gets allocated here?
I think, it gets allocated during declaration itself.Correct me if I am wrong.
malloc and friends.static variables are allocated in the data section if they have initialization values (static int a=1;), otherwise they will implicitly be zeroed out and allocated in the BSS section (static int a;). They are initialized before calling main.As for your specific example,
int i;
i = 10;
the compiler will allocate i on the stack frame. It will probably set the value right away. So it will allocate and initialize it when entering that scope.
Take for instance
#include <stdio.h>
int main()
{
int foo;
foo = 123;
printf("%d\n", foo);
}
Now compile this with
gcc -O0 a.c -S
This produces the assembly file a.s. If you inspect it, you will indeed see that foo is copied right on the stack frame:
movl $123, -4(%rbp)
or, in Intel syntax (add -masm=intel to gcc):
mov DWORD PTR [rbp-4], 123
Right below that you will see a call printf.
The RBP register refers to the stack frame, so this variable in this case only ever exists on the stack frame, because it's only used in the call to printf.
Memory can be allocated:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With