Assume that the function func has bugs so that it leaks memory.
pid_t childPid;
int status;
childPid = fork();
if (childPid == -1)
errExit("fork");
if (childPid == 0) /* Child calls func() and */
exit(func(arg)); /* uses return value as exit status */
/* Parent waits for child to terminate. It can determine the
result of func() by inspecting 'status'. */
if (wait(&status) == -1)
errExit("wait");
Question 1>
If a program leaks memory, after the program exits in the end, does it still leak memory or system will collect all memory allocated by the program and there is no more leaked memory?
Question 2>
After the parent process calls the wait, how is the leaked memory caused by the func in child process?
The system will collect all the memory resources from the child, and there will no longer be any leaked memory from the child process. Also a call to
fork()separates the memory space of the parent and child, therefore a leak in the child process will not leak in the parent process unless you call the same buggy function in both.Calling
wait()in the parent, and the child leaking memory really have nothing to-do with each other. The call towait()in the parent merely causes the parent to block waiting for a signal indicating that a child process has completed. The child will still have to callfunc()first before it can complete, since it must pass the return value offunc()toexit(). Thereforefunc()can still technically “leak” memory in that it allocates some memory on the heap, but doesn’t clean it up, even though the clean-up actions by the OS takes place almost immediately afterfunc()is called. In other words after the call toexit()is complete, the OS has released the resources used by the child, butfunc()itself can still fail to free any memory it tried to allocate.