Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 243
Ramy Al Zuhouri Avatar asked Jan 19 '26 07:01

Ramy Al Zuhouri


1 Answers

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.

like image 102
perreal Avatar answered Jan 21 '26 23:01

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!