0
#include<stdio.h>
int main()
{
  int a;
  printf(" %u ",&a);
  return 0;
}

When we associate '&' with a variable the address we get is the virtual address when we run the program on a system with virtual memory. Then why swapping in and out a process gives different address many a time.
see image

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    You'll have to explain why you feel the address should be the same across program invocations. – pvg Sep 17 '17 at 07:23
  • because logical address of a process is the distance between the location of variable in RAM and location of start of address space for the process i.e. relative location of variable with respect to start of it's address space which will be same for both parent and child since data is cloned. – Shashank Rao Sep 17 '17 at 07:38
  • This is highly specific to the implementation of the OS, C doesn't give you any such guarantees. In the case of linux, you probably want to be reading up on `execve` and related. – pvg Sep 17 '17 at 07:46
  • 1
    https://en.wikipedia.org/wiki/Address_space_layout_randomization – Mat Jun 22 '18 at 14:29
  • 3
    There's a big difference between *swapping* a program image into and out of physical memory, and running the same program multiple times. Swapping very well may change physical addresses, but should not change any virtual ones. Running a program anew is a different story, and carries no particular guarantees at the C language level. – John Bollinger Jun 22 '18 at 14:29

0 Answers0