-1

Kindly explain the difference between the virtual and physical addresses based on the following example. Please explain which address is specifically used here and how to use the other address in the same place. Also, how can the two always be distinguished.

code:

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

What address does &a refer to in both the statements?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

0

&a may refer two different addresses if you declare variable a independently in if & else blocks.

But if variable a is declared above "if",then in either of the case, variable "a" will be having the same physical address which can be accessed by &a.

When you add or subtract values from "a", you are altering the content stored in the memory where "a" is stored, means the value of a, not the address.

In you case, you are not altering the address of a, as it is the physical address.

If you really want to play with the address then have a pointer pointing to a like

 *p = &a;
 p+=5;
 p-=5;

This way you can go five memory blocks forward & backward (one block size depends on type of variable "a") in memory.

For more on virtual address: refer here

Hope that helps.

Community
  • 1
  • 1
Balram Tiwari
  • 5,657
  • 2
  • 23
  • 41
  • Except for the comment that it is the physical address, I agree with what's written here. Only the lowest reaches of the kernel work with physical addresses. All other code works with virtual addresses. In particular, user programs in systems like Unix work only with virtual addresses, and the kernel controls the mapping from virtual to physical addresses and the MMU handles that mapping. There is essentially no way to determine a physical address corresponding to a virtual address from the user code. – Jonathan Leffler Apr 04 '15 at 17:41