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:
-
*p is copied to some other part of the heap, p is updated to reflect the newly copied location.
-
p still points to the original. if any child runs free(p); the parent may be unable to access it.
-
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?
When forking, child process becomes a copy of its parent. That includes any dynamically allocated memory. So the memory will be copied. Pointer address will stay the same (copy doesn’t change data, remember?), which is achieved by virtual addressing. Don’t forget to call
freein both parent and child processes.