Am I correct? Am I wrong? If the latter what does actually happen?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With