0
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>

int main(int argc, char *argv[]){
    int split;
    pid_t childpid;

    char *x = argv[1];
        
    int status;
    char splitindex_string[40];
    split = atoi(x);    
    printf("%d\n" ,split );
    
    int indexfile_split = 320000/split;

    snprintf(splitindex_string,40, "%d", indexfile_split);
    
    childpid = fork();

    if(childpid==0){
        execlp("/bin/split", "split", "l", splitindex_string, "-a", "1" ,"-d", "input.txt", "output",  NULL);
        return 0;
    }

    else{
        int status;
        wait(&status);

        return 0;
    }
}

我有这个 c 代码,但是当我运行输出时,我不断收到这个奇怪的分段错误(核心转储)错误。代码编译得很好,只有在我运行二进制文件后才会出现错误。从我在线阅读的内容来看,我可能正在访问无效的内存。我已经盯着这个看了好几个小时了。帮助将不胜感激谢谢

4

2 回答 2

1

问题是错过了对输入的检查。如果您不向可执行文件提供参数,它会崩溃,并给您您所说的错误。

我建议您在访问它们之前对提供的参数进行检查。

于 2020-10-09T09:54:11.843 回答
1

您需要检查您的程序是否被正确调用,例如:

int main(int argc, char *argv[]){
    if (argc < 2)
    {
       printf("You didn't provide enough arguments\n");
       return 1;
    }

    int split;
    pid_t childpid;
    ...

如果argc <2 thenargv[1]不存在并且取消引用它将导致未定义的行为。

于 2020-10-09T10:11:42.473 回答