In C, each function has an activation record which is allocated on a stack frame. Local variables are allocated in their own function's activation record. So, what is the case with global variables? Where are they allocated?
For example
#include <stdio.h>
int a;
void v()
{a= 2;
int b;
b++;
}
main()
{
int f;
printf("\n%d",a);
v();
}
-----Activation record----
-------------------
-------------------
activation record for main
-------------------
int f
-------------------
-------------------
activation record of v
--------------------
int a
--------------------
int b
--------------------
---------------
Where is variable x
stored according to the activation record logic?
Wrong, an optimizing compiler might not do that (and
gcc -O3 -flto
won't, on Linux / x86-64 with a recent GCC). It will inline some functions. Some locals are only kept in some processor registers (so have no memory location). Read about register allocation, e.g. in the Dragon Book or some other textbook about compilers. Be aware of automatic variables. Be also aware that you don't even need a computer to run a C program (a good way of teaching C is to have the classroom play being a computer; and you could run a C program on paper with a pencil).The globals are usually not in practice on the call stack (which hold call frames or activation records). They might sit in the data segment (and could be optimized out entirely).
The C11 specification does not require any call stack. Check by reading n1570. Some implementations don't use any call stack (or activation records). Be aware of the crt0 calling your
main
.Read linkers and loaders for more. Read also a textbook about operating systems.
On Linux, try
cat /proc/self/maps
to understand the virtual address space of the process running thatcat
command; see proc(5)Look into the assembler code generated by
gcc -O2 -fverbose-asm -S
, using Linux. Read about invoking GCC.See also this answer.
On Linux, play with nm(1), readelf(1), objdump(1) on your executable or object file (in ELF format).