When I write
int main()
{
int j;
}
The memory for j
is allocated at the time of compilation, but when during compilation?
In C, main is compiled the same as every other function: any variables declared in main will be "allocated" on the stack. A stack frame is the portion of the stack that is used by a single function call. The frame contains slots for all of the locals used within a function. This memory is considered temporary since when the function returns, this frame will be popped off the stack.
The C compiler will assign a static address to global variables. This address is considered part of the binary's "image" and as such has a static location in memory. The C compiler knows the size of every type, so it can set aside the appropriate amount of space in the memory layout of the binary for each global variable. Then, any code that accesses this variable will simply reference this address instead.
You can examine a variable's address with code like this:
#include
int i;
void foo(int n)
{
if(n > 2)
return;
printf("From foo &n = %xd\n", &n);
printf("From foo &i = %xd\n", &i);
foo(n+1);
}
int main()
{
printf("&i = %xd\n", &i);
foo(0);
return 0;
}
Running this code produces output similar to:
./a.out
&i = 600934d
From foo &n = 38bc4efcd
From foo &i = 600934d
From foo &n = 38bc4eccd
From foo &i = 600934d
From foo &n = 38bc4e9cd
From foo &i = 600934d
There are two things you should notice here:
foo
changes with each call to foo. In fact, it will decrease every time, since the stack grows downward.