Take the 2-minute tour ×

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;

// 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?

share|improve this question
Pointers still point to the same memory address. What is updated is the virtual mapping. Pointer -> virtual address -> real physical address. –  jweyrich Sep 29 '11 at 17:36
possible duplicate of Referencing pointers after a fork() call in C –  Marc B Sep 29 '11 at 17:38
add comment

3 Answers

up vote 8 down vote accepted

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 free in both parent and child processes.

share|improve this answer
thanks. the virtual addressing part is really what I didn't understand. –  Dmitri Oct 2 '11 at 4:09
add comment

The value is also copied, as fork copies code, globals, heap and stack.

Source : http://web.eecs.utk.edu/~huangj/cs360/360/notes/Fork/lecture.html

share|improve this answer
add comment

Malloced memory comes from the heap, which is just a fancy word for a set of memory pages. Since fork() copies all of a process's memory pages regardless of any fancy naming they've been given in textbooks, pointers returned by fork() work just fine in the child :-)

share|improve this answer
add comment

Your Answer


