-
strdup() and execvp()
I am working on an intro to OS book and have some questions about this code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0) { // fork failed
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) { // child (new process)
printf("hello, I am child (pid:%d)\n", (int) getpid());
char *myargs[3];
myargs[0] = strdup("wc"); // program: "wc" (word count)
myargs[1] = strdup("p3.c"); // argument: file to count
myargs[2] = NULL; // marks end of array
execvp(myargs[0], myargs); // runs word count
printf("this shouldn’t print out");
} else { // parent goes down this path (main)
int wc = wait(NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",
rc, wc, (int) getpid());
}
return 0;
}
Because I am using strdup() to create this new strings, shouldn't I be free()ing the pointers? Or does execvp() somehow handle this?
The book says the heap and stack and other parts of the memory space of the program are reinitialized. I know that these pointers reside in the heap, but what does it mean to be "reinitialized"?
-
On execve() (which execvp() winds up calling), any allocated memory is freed, so you're fine. That's probably what the author means by reinitialized: set back to the initial state, i.e. the memory is freed.
How exactly it's freed is going to be system-dependent, but it will probably include things like an implicit munmap() of mmap()ed memory, setting the program break to its initial value, etc.
-