I mean to ask about the preservation of string literals within a call to execve
family. From OSTEP Chp.4:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main (int argc, char *argv[]) {
...
int rc = fork();
...
if (rc == 0) {
char *myargs[3];
myargs[0] = strdup("wc");
myargs[1] = strdup("p3.c");
myargs[2] = NULL;
execvp(myargs[0], myargs);
}
I denote ...
as irrelevant to my question. I wanted to ask about the code here. As I understand it, C sets up myargs
to be presented as the char *argv[]
of the main function of wc
. I want to understand the concept to do with string literals. From my understanding, the C standard allows the mutability of the argv
. For example:
int main (int argc, char *argv[]) {
argv[0][2] = 'd';
}
However, I'm wondering how this can be guaranteed when these character arrays are fixed length. Additionally, why was strdup()
called? From my understanding, this will heap-allocate the string, allowing it to be mutated, so is this necessary when calling execvp()
or would:
myargs[0] = "wc";
be acceptable?