For example if I have this code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int *ptr;
int
main(void)
{
ptr = malloc(sizeof(int));
if (ptr == NULL)
return (1);
if (fork() == 0) {
(*ptr)++;
printf("in child process\n");
printf("%d\n", *ptr);
}
(*ptr)++;
printf("%d\n", *ptr);
return (0);
}
I was wondering when the child process is started and the memory is copied, is a copy of the pointer ptr created, or is the actual memory where it points to also copied. In short, I am wondering if a datarace will happen, between the child and the parent, or will each have a different copy of the pointer ptr pointing to different locations in memory, or will each have a different copy of the pointer with both pointing to the same location in memory.
wondering what happens when I fork while using pointers to store variables,
This does not result in a race.
fork()creates a new process (not a thread) and has a copy of all the variables. From the man pages:Note that
(*ptr)++;causes UB asptrpoints to uninitialized memory.