When calling malloc in the parent and child processes after fork, the result is different depending on the OS.
Here's a simple program to illustrate this:
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
void malloctest(int cont, int value)
{
int max = 1;
int *var1 = malloc(sizeof(int));
if(var1 == NULL)
exit(EXIT_FAILURE);
*var1 = value;
sleep(value);
printf("pid=%d, ppid=%d, address=%p, value=%d\n", getpid(), getppid(), var1, *var1);
if (cont < max)
{
switch (fork())
{
case -1: //error
perror("fork");
exit(EXIT_FAILURE);
case 0: //child
malloctest(cont + 1,5);
_exit(EXIT_SUCCESS);
default: //parent
sleep(1);
malloctest(cont + 1,1);
wait(NULL);
}
}
}
int main(int argc, char const *argv[])
{
malloctest(0,0);
}
In macOS Darwin 20.6.0 Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64 i386
, malloc returns different addresses
pid=63430, ppid=60230, address=0x7f9199405bd0, value=0
pid=63430, ppid=60230, address=0x7f9199504080, value=1
pid=63431, ppid=63430, address=0x7f91995041e0, value=5
whereas in Linux, Linux 4.15.0-58-generic #64-Ubuntu SMP Tue Aug 6 11:12:41 UTC 2019 x86_64
, malloc returns the same address in parent and child
pid=10314, ppid=3797, address=0x561284e5b260, value=0
pid=10314, ppid=3797, address=0x561284e5b690, value=1
pid=10315, ppid=10314, address=0x561284e5b690, value=5
Is this something to worry about? Or is it just an implementation detail as in, the OS can afford to return the same address because it uses the copy-on-write technique to maintain separate copies of the values pointed to by parent and child? Whereas macOS assigns different addresses straight away