简体   繁体   中英

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

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?

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.

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

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM