PDA

View Full Version : Compiler's calculation on memory/address

vermarajeev
10th October 2007, 07:33
Hello All,
How is an address being calculated by the compiler? or what does the compiler do internally when I write the following:
For example:
When I say

int a;
some memory is allocated with some address by the compiler. My question is how?
As per my understanding, the compiler takes the sizeof datatype which is "int" in above case and then does some manipulation to calculate the address which is a part of memory?

Michiel
10th October 2007, 08:01
You're allocating an int as a local variable on the stack. Take a look at this (http://en.wikipedia.org/wiki/Call_stack). For each variable (local and parameter) the compiler knows the offset from the frame pointer.

vermarajeev
10th October 2007, 11:12
You're allocating an int as a local variable on the stack. Take a look at this (http://en.wikipedia.org/wiki/Call_stack). For each variable (local and parameter) the compiler knows the offset from the frame pointer.

The link tells only about the call stack. My question was how does the compiler calculate the address of a variable? I mean,

For example:

int main()
{
int a = 10;
cout<<&a<<endl;
}

On my system the address is 0012FED4.
I want to know how is the address "0012FED4" calculated by the compiler? Any idea...

Thanks

wysota
10th October 2007, 11:25
It's exactly as Michiel said. "a" is placed as the first (or second, or third) variable on the stack. There is a register that holds the current frame pointer that points to the beginning of the stack frame. The frame contains things like the return address and the previous frame pointer. After that local variables (your "a" included) are placed. So the compiler knows, that to reference "a" it has to go to the address pointed by "FP" (frame pointer) and substract (or add, depending on the architecture) for instance "12". Every time you reference "a", the compiler changes that to "\$FP-12".