在我的 C 程序中,我使用 execvp 命令来解析输入并运行它。 我有这个:
char read_str[MAX_ALLOWED_BUFFER];
pid_t child_pid;
char *strs[100] = {NULL};
child_pid = fork();
if (child_pid == 0) {
split(read_str, strs);
execvp(strs[0], strs);
printf("Failed\n");
}
else {
waitpid(child_pid, NULL, 0);
for (y = 0; y < 100; y++) free(strs[y]);
}
还有这个函数
void split(char *str, char **splitstr) {
char *p;
int i=0;
p = strtok(str," ");
while(p!= NULL) {
splitstr[i] = malloc(strlen(p) + 1);
if (splitstr[i]) strcpy(splitstr[i], p);
i++;
p = strtok(NULL, " ");
}
}
第一个代码块处于 while 循环中,并不断询问用户输入。无论如何,如果 execvp 返回,则发生错误并打印失败,然后如果我再键入两个有效命令,我将收到内存损坏错误...
有没有人看到我在这里做错了什么?
最佳答案
what I am doing wrong here
几件事。
- 当
execvp
失败时, child 会转到 while 循环的开头,现在您 child 和 parent 都在读取输入。您要做的是在打印"Failed"
之后exit(1)
。 - 如果你这样做了,那么
strs
永远不会在父级中分配,也不需要free()
d。您可以将strs
的定义移动到if (child_pid == 0) {
中,您永远不必担心free
任何东西。
这并不能解释你的内存损坏问题,它是这样的:
- 失败的
execvp
使子级C1
读取输入。C1
的strs
数组中有malloc()
编辑的条目。 - 现在
C1
获取输入,fork()
的C2
和waitpid
用于它。然后C1
在strs
条目上调用free
,它们变成悬垂的(您应该将它们NULL
)。< - 现在
C1
再次获取输入,fork
C3
,waitpid
获取它,并调用free
再次在 samestrs
条目上,导致双重free
和您观察到的损坏。
关于c - execvp 导致内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420749/