11

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.

1
  • 2
    If you have statically allocated a buffer to hold your path it must be at least the maximum length that a Linux absolute path can be. A google search reveals this to be 4096 (from /usr/src/linux-2.4.20-8/include/linux/limits.h, #define PATH_MAX 4096 /* # chars in a path name including nul */). So you should be including limits.h and making your buffer PATH_MAX characters in length. Commented Sep 12, 2010 at 1:18

1 Answer 1

9

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

Re file descriptors, 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().

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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().
@DavidRTribble The exec() arguments are copied into kernel space by virtue of it being a system call. Nothing special about exec() in this respect.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.