1

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,

  • 4
    The child gets a complete, exact copy of the entire virtual address space. Pointers are stored in that space. They point to data within the space. There can be no race. – Gene Apr 30 '23 at 06:14
  • 2
    `(*ptr)++;` has undefined behavior since haven't initialized the `int` though. – Ted Lyngmo Apr 30 '23 at 06:40

1 Answers1

0

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:

fork() causes creation of a new process. The new process (child process) is an exact copy of the calling process (parent process) except for the following:

       •   The child process has a unique process ID.

       •   The child process has a different parent process ID (i.e., the
           process ID of the parent process).

       •   The child process has its own copy of the parent's descriptors.
           These descriptors reference the same underlying objects, so
           that, for instance, file pointers in file objects are shared
           between the child and the parent, so that an lseek(2) on a
           descriptor in the child process can affect a subsequent read or
           write by the parent.  This descriptor copying is also used by
           the shell to establish standard input and output for newly
           created processes as well as to set up pipes.

       •   The child processes resource utilizations are set to 0; see
           setrlimit(2).

Note that (*ptr)++; causes UB as ptr points to uninitialized memory.

babon
  • 3,615
  • 2
  • 20
  • 20