Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does malloc + fork create a memory leak?

Tags:

fork

unix

malloc

  1. Parent process does malloc()
  2. fork
  3. parent modifies the allocated block
  4. CoW kicks in and creates one copy of the modified block while keeping the old copy in place
  5. The child doesn't know or care about the parent's stuff and doesn't call free() on its copy of it
  6. Memory leak!

Am I correct? Am I wrong? If the latter what does actually happen?

like image 274
Martin Sustrik Avatar asked Nov 17 '25 08:11

Martin Sustrik


1 Answers

Neither the malloc() nor the fork() creates a leak — so I suppose you're wrong.

The parent has its own copy of the allocated block. It may do as it wishes with it. The child has its own copy of the allocated block. It too may do as it wishes with it. If the child ignores the block, it is not a leak (yet). If the child blithely tramples a pointer, or returns from a function that holds the only pointer to the allocated memory without releasing it first, that would lead to a leak. But it isn't the fork() or the malloc() that's at fault.

Remember, the same code is running after the fork() — the major difference between the processes is the PID and the return value from fork(). Everything else (almost everything else — see the POSIX specification of fork() for the details) is the same. So, if the code leaks, that's a bug introduced by the programmer — it is not the fault of either malloc() or fork().

Note that if the child uses one of the exec*() family of functions, all the allocated memory from the original process is released. The new process gets new memory allocated. Similarly, if the child exits, then the memory will be released. There isn't a long-term risk of the O/S losing track of memory.

like image 71
Jonathan Leffler Avatar answered Nov 21 '25 01:11

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!