5

Consider the following code snippet.

if (fork() == 0)
{
     a = a + 5;
     printf("%d, %d \n", a, &a);
}
else
{
     a = a - 5;
     printf ("%d, %d \n", a,& a);
}

AFAIK, when fork() is made, the virtual address space of parent is copied to the child and both child & parent share the same physical pages until one of them tries to modify. The moment one of the child & parent modifies a variable, the physical page of parent is copied to another page for child and the physical pages remain private. So, here value of 'a' is different in child & parent. But when it comes for the addresses of 'a' in child & parent, the output is same. I am not able to figure out why the address remains same even if the physical pages are diffrent.

Green goblin
  • 9,898
  • 13
  • 71
  • 100

2 Answers2

7

The address of a is not the actual physical address.

It is a virtual address.
The hardware/OS layer maps virtual addresses to physical addresses (invisibly to your application).

So even though the addresses have the same number they do not map to the same physical memory on your ram chip.

PS. When printing the address (ie pointer) using printf() best to use "%p"

Martin York
  • 257,169
  • 86
  • 333
  • 562
3

The response is almost in your question: the physical page of a is copied (and thus not the same as in the parent process) after modifying a, but the virtual address (what's seen by your program, through &a) does not change.

In fact it would be very awkward to change the virtual address of a when assigning it a new value. Consider what happens if you had previously stored a pointer to a:

 int *p = &a;
 a = a - 5;
 printf("%d", *p)

After the second line p would not point to a anymore, a behaviour that no programmer would expect.

The use of copy-on-write for physical pages is an optimization of the OS that is irrelevant to the behavior of your program: you can consider that the entire address space is copied when you fork.

Antoine
  • 5,158
  • 1
  • 24
  • 37