In the program given below virtual address for both process is same. I understood the reason for global variables but could not understand for local variables.
how is virtual addresses assigned to local variables before running?
int main()
{
int a;
if (fork() == 0)
{
a = a + 5;
printf(“%d,%d\n”, a, &a);
}
else
{
a = a –5;
printf(“%d, %d\n”, a, &a);
}
}
While compiling, the compiler decides to use either the stack or a register for local variables. In this case, the stack.
It also decides where in the (virtual) address space to place the stack.
So for both processes the stack starts in the same (virtual) address. And since the flow of this specific program is rather deterministic, the stack frames look exactly the same for both processes, resulting in the same offset in the stack for ‘a’.