Search code examples
cforkheap-memory

Two processes sharing the same heap


I haven't understood something about processes generated with fork(). If I try a code like this one:

int main(int argc, char** argv)
{
    void* mem=malloc(100);
    pid_t pid=fork();
    printf("%p\n",mem);
}

Both processes print the same address. So do they point at the same area of memory in the heap? Isn't that dangerous? There may be a conflict. My book says that the values on the stack are copied, but it does not talk about heap.


Solution

  • Different processes are contained in separate virtual address spaces so those memory addresses point to different memory locations.

    As Karoly Horvath suggests, it is a bit more complicated due to an optimization called copy-on-write, which basically allows having a single copy until a distinction is needed. This is implemented through page-faults and in the end same addresses in two separate virtual address spaces do not refer to the same memory location.