mikeizbicki / ucr-cs100

open source software construction course
Other
485 stars 407 forks source link

Dynamic memory allocation within child process #258

Closed aorti017 closed 9 years ago

aorti017 commented 9 years ago

If you were to dynamically allocate memory within a child process, what happens to that memory when the child process is terminated? Would this cause a memory leak or would the termination of the process clear the memory?

mikeizbicki commented 9 years ago

Good question.

Memory is allocated separately for each process. A memory leak is when a process exits but has not freed some of its memory. So if the child process calls new without calling delete, this will cause a memory leak in the child but not the parent.

Is this a bad thing? That depends.

If you dynamically allocate the memory you pass to execvp, then it is impossible to free that memory. That's because any code that comes after execvp won't get executed. This is technically a "memory leak." But it's not really a big deal because we know ahead of time exactly how much memory is leaking and where it will be freed in the future.

It is possible to allocate the memory you need for execvp on the stack using the alloca syscall. This is the technically correct way to do things, but you are not required to do that for this assignment. You only need to ensure the parent rshell process doesn't have memory leaks.

abarb014 commented 9 years ago

I'm confused. So dynamically allocated memory will be lost in the child process, but we need to allocate memory in order to create the char double pointer to use for execvp? Is that the cause of the memory leak you talked about? Or are you saying that any instances of new in the child process will be lost? The example you used in class was along the lines of argv[0] = new char[3], so passing argv to execvp in this case will cause a memory leak?

mikeizbicki commented 9 years ago

In class I called new in the child process, but never called delete. This is a memory leak. But that's okay, if the leaked memory is the arguments to execvp.