execv
标头中声明的函数的签名unistd.h
是
int execv(const char *path, char *const argv[]);
请注意,这与
int execv(const char *path, char *const *argv);
这意味着这argv
是指向类型对象的指针char * const
,即指向字符的常量指针。此外,手册页execv
说 -
按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。指针数组必须以 NULL 指针终止。
此外,list
其类型为char **
的赋值与 的第二个参数兼容execv
。我建议进行以下更改 -
// +1 for the terminating NULL pointer required for the
// second argument of execv
char **list = malloc((argc + 1) * sizeof *list);
if(list == NULL) {
printf("not enough memory to allocate\n");
// handle it
}
int i = 0;
for(i = 0; i < argc; ++i) {
// strdup returns a pointer to a new string
// which is a duplicate of the string argv[i]
// this does effectively the same as the commented
// out block after the below statement.
// include the header string.h for the prototype
// of strdup POSIX function.
list[i] = strdup(argv[i]);
/*
list[i] = malloc(strlen(argv[i])+1);
if(list[i] == NULL) {
printf("not enough memory to allocate\n");
// handle it
}
strcpy(list[i], argv[i]);
*/
}
list[argc] = NULL; // terminate the array with the NULL pointer
execv(list[0], list);