简体   繁体   English

分段错误(核心转储)运行时错误

[英]Segmentation fault (core dumped) runtime error

#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;
    }
}

i have this c code, but when i run the output i keep getting this weird segmentation fault (core dumped) error.我有这个 c 代码,但是当我运行输出时,我不断收到这个奇怪的分段错误(核心转储)错误。 the code compiles fine, the error only appears after i run the binary.代码编译得很好,错误只在我运行二进制文件后出现。 from what I read online im probably accessing invalid memory.从我在线阅读的内容来看,我可能访问了无效内存。 Ive been staring at this for hours now.我已经盯着这个看了几个小时了。 help would be appreciated thanks帮助将不胜感激谢谢

The problem is the missed check over input.问题是错过了对输入的检查。 If you don't provide argument to the executable it crash, and give you the error you say.如果你没有为可执行文件提供参数,它就会崩溃,并给你你说的错误。

I suggest you to introduce a check over the argument provided, before accessing them.我建议您在访问它们之前对提供的参数进行检查。

You need to check if your program is invoked correctly, for example like this:您需要检查您的程序是否被正确调用,例如:

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

    int split;
    pid_t childpid;
    ...

If argc <2 then argv[1] doesn't exist and dereferencing it will result in undefined behaviour.如果argc <2argv[1]不存在并且取消引用它会导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM