Does malloc + develop a memory leak?

  • The parent process does malloc ()
  • fork
  • parent modifies the selected block
  • CoW starts and creates one copy of the modified block, while keeping the old copy.
  • The child does not know or care about the parent material and does not call free () on its copy
  • Memory leak!

Am I correct? Am I wrong? If the last thing really happens?

+3


source to share


1 answer


Neither malloc()

nor fork()

does it leak, so I am assuming you are wrong.

The parent has its own copy of the selected block. He can do what he wants. The child has his own copy of the selected block. He, too, can do what he wants. If the kid ignores the block, it's not a leak (yet). If the child blithely tramples on a pointer or returns from a function that contains a single pointer to allocated memory without releasing it first, it will leak. But this is not a mistake fork()

or malloc()

.



Remember, the same code works after fork()

- the main difference between processes is the PID and the return value from fork()

. Everything else (almost everything else - see the POSIX Specification fork()

for details) is the same. So, if the code is leaking, the error introduced by the programmer is not an error either malloc()

or fork()

.

Note that if the child uses one of the function families exec*()

, the allocated memory is freed from the original process. The new process gets new allocated memory. Likewise, if the child comes out, then the memory will be released. There is no long-term risk of O / S memory loss.

+4


source







All Articles