views:

86

answers:

1

I'm writing a simple shell as an OS course assignment, I need to search in the PATH to find the program user typed in, once I find the right directory, I malloc a piece of memory just enough to hold the directory name plus the program name, and I pass it as the first argument to execv().

I could have statically allocated 100 characters or so, but having a limit makes me feel uncomfortable. So when execv() executes, is the heap cleaned up or is that piece of memory lost?

It's maybe not a lot of memory but I'm just curious.

+5  A: 

When you exec(), the entire process is (a) ended, so all resources, including fd's and dynamic memory, are reclaimed by the operating system, and (b) replaced: code, data, threads, ...

Correction: not all file descriptors are reclaimed. From "man execve":

 File descriptors open in the calling process image remain open in the new
 process image, except for those for which the close-on-exec flag is set
 (see close(2) and fcntl(2)).  Descriptors that remain open are unaffected
 by execve().
EJP
Perhaps it's obvious but that is only true for a successful exec. If unsuccessful, the original process will continue with the dynamically allocated memory still allocated.
mark4o
In other words, the `exec()` call allocates its arguments somewhere in memory out of the original process space, so that when it replaces the executable image with the exec'd program, those arguments are on the new initial call stack for `main()`.
Loadmaster