- Local function variables are allocated on the stack frame and initialized when you call the function.
- Arguments passed to functions are either on the stack or passed through registers. This depends on your calling convention.
- They can be allocated on the heap, if you use
malloc
and friends.
- The
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
.
int i
: if block scope, at the entry of the blocki
is declared, see my answer.int i
. Edit ok got your point, you are correct thanks{
symbol