Consider the below program.
int a = 0x45;
int main()
{
int i = a;
return 0;
}
;; asm code
call 0x401780 <__main>
mov 0x402000,%eax // why does it allocate 0x402000 only for global 'a'?
mov %eax,0xc(%esp)
mov $0x0,%eax
leave
This is the equivalent assembly code generated in CodeBlocks on Windows/xp.
I understand 0x402000
is data segment address. But is that memory location hardcoded by compiler?
I think it is not hardcoded because that memory location may / may not be used by other applications too.
As we know, Operating system allocates Stack frame for local variables and returns base addess of stack frame. and local variables are accessed using %esp and %ebp
registers with offset.
Does the operating system do the same for global variables? If it does the same why the value is hardcoded?
dw a 0x40; this directive allocates memory on data segment
mov %ax,a; copies value of a to accumulator
But how does compiler know 'a' has memory address 0x402000
. If compiler has hardcoded the value as 0x402000
it should first make sure that address is not used by another application right?
If operating system allocates memory on datasegment, the memory address should be varied depending upon the applications and resources. Could anyone explain what really happens when I define global variables?