简体   繁体   中英

If the address of a pointer is copied over when forking, how is it that the value the pointer is pointing to is unique to each child process?

I understand that in theory, (not considering copy when write), fork creates a child process with an identical copy of the process control block of the parent process. This means that the values in the data, stack and heap are all copied over. However, I wanted to see if how that interacted with pointer values/ values being pointed to. I did this experiment.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

int *pointer;

int main () {
   pointer = malloc(sizeof(int));
   *pointer = 3;
   printf("initial pointer value %p\n", pointer);
   printf("pointer points to value: %d\n", *pointer);
   int PID = fork();
   if (PID == 0) {
       printf("child pointer value %p\n", pointer);
       *pointer = 9;
       printf("child pointer points to value: %d\n", *pointer);
   } else {
       wait();
       printf("parent pointer value %p\n", pointer);
       printf("parent pointer points to value: %d\n", *pointer);
   }
}

I expected 1 of 2 scenarios: Either the pointer was copied over with the same address, and thus changing the value at said address would change the value being pointed to in both processes (both 9). Or, the value being pointed to was copied over, but the address of the pointer would be different.

But instead I got this:

initial pointer value 0x1791010
pointer points to value: 3
child pointer value 0x1791010
child pointer points to value: 9
parent pointer value 0x1791010
parent pointer points to value: 3

ie despite address being copied over for both processes, changing the value being stored at the address "0x1791010" did not change the value being stored in the SAME address in the parent. How is this possible? Do the addresses value not point to a unique section of memory in the computer?

So thanks to the very quick response, I understand now that the reason is virtual memory. The address refers to the address of pointer refers to an address in the memory space, but not the physical memory storing said value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM