Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens to pointers to dynamically allocated memory after a UNIX fork?

Tags:

Someone please clarify what happens with pointers after a fork().

As I understand it, pointers to anything on the stack or statically allocated are relative to the stack/data segment registers, so copying them exactly during a fork is OK.

However, what happens if I malloc() something before forking? for example:

void* p = malloc(64);
// put something in *p;
fork();

// what happens to p and the memory i allocated here?

possibilities I am thinking of:

  1. *p is copied to some other part of the heap, p is updated to reflect the newly copied location.

  2. p still points to the original. if any child runs free(p); the parent may be unable to access it.

  3. p still points to the original data, but the child process does not have rights to access/manage the memory.

which of these, if any, is correct?