Why is the address of the variable of the child process and the parent process the same

Here is my code

int main() { pid_t pid; int y = 3; if ( (pid = fork()) <0 ) return -1;; if( pid == 0 ) /* child */ { printf(" before: %d %p\n", y, &y ); y *= 10; printf("after: %d %p\n", y, &y ); } else /* father */ { sleep(1); printf("father: %d %p\n" , y , &y ); } return 0; } 

The output of the program is as follows:

 before: 3 ffbff440 after: 30 ffbff440 father: 3 ffbff440 

My question is: why is the address of the variable child and parent the same, but the value is different?

+8
c unix fork
source share
2 answers

Because it is a virtual address, not a physical one.

Each process gets its own address space (for example, a 32-bit system can allow each process to have its own address space with a full 4G range).

This is a memory management unit that will map virtual addresses to physical ones (and handle things like page errors if paged pages need to be redeemed from secondary storage).

The following diagram may help, each section represents a 4K memory block:

  Process A Physical Memory Process B +-------+ +-------------+ +-------+ 0K | |----> 0K | (shared) | <----| | 0K +-------+ +-------------+ +-------+ 4K | |--+ 4K | | <----| | 4K +-------+ | +-------------+ +-------+ 8K | | +-> 8K | | | | 8K +-------+ +-------------+ +-------+ | : : : : : : : | | +-------------+ | | 128K | | <--------+ | +-------------+ +--------> 132K | | +-------------+ 

You can see in this diagram a disconnection between virtual memory addresses and physical memory addresses (as well as the ability for processes to share memory blocks). The addresses on the left and right are the virtual addresses that the processes see.

The addresses in the central unit are the actual physical addresses where the data is "valid", and the MMU processes the mapping.

For a deeper explanation of fork (and exec ), you can also see this answer .

+21
source share

The address is โ€œthe sameโ€ as each process has its own virtual address space, and the variable is usually loaded in the same place. Please note that this is not a physical address in memory. Also note that there are schemes that deliberately rank the location where the process is loaded to make it more difficult to attack / crack the process. In this case, the address will be different.

+1
source share

All Articles