有人能向我解释一下为什么我在这段代码上有一个分段错误吗?我一直在努力弄清楚,在各种搜索中都是空的。当我不调用main(argc,argv)运行代码时,它就会运行。从只将argv中的2个数字转换为int,然后返回它们。谢谢。
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int i;
int* sums;
sums[argc];
pid_t cpid;
int status;
char* args[10];
int count = 1;
for(i = 0; i < (argc / 2); i++) {
cpid = fork();
if(cpid == 0) {
args[1] = argv[count];
args[2] = argv[count + 1];
execvp("./slave", args);
} else {
waitpid(cpid, &status, 0);
sums[i] = WEXITSTATUS(status);
printf("Child returned the number %d\n", sums[i]);
sprintf(argv[i+1], "%d", sums[i]);
}
count += 2;
}
if(sums[0] == 0) {
printf("done\n");
} else {
main(argc/2, args);
}
}发布于 2018-10-10 00:43:24
第一个问题是您没有为sums分配任何内存,sums[i]访问一个垃圾位置。这样做:
int sums[argc];其次,对于execvp函数参数数组,必须有1. -合法字符串。2.最后一个元素3必须为空
args[0] = "some-execution-file-name";
args[1] = argv[count];
args[2] = argv[count + 1];
args[3] = NULL;否则,函数就不知道数组的大小,而从函数可以在读取元素时死掉。
https://stackoverflow.com/questions/52731050
复制相似问题