【问题标题】:Segmentation fault (core dumped) runtime error分段错误(核心转储)运行时错误
【发布时间】:2020-10-09 09:19:32
【问题描述】:
#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 代码,但是当我运行输出时,我不断收到这个奇怪的分段错误(核心转储)错误。代码编译得很好,只有在我运行二进制文件后才会出现错误。从我在线阅读的内容来看,我可能正在访问无效的内存。我已经盯着这个看了好几个小时了。帮助将不胜感激,谢谢

【问题讨论】:

  • 这是c还是c++? (它不是可移植的 c++ afaik)
  • 它的 c 代码不是 c++(我为不恰当的标签道歉)
  • 在 Linux 上,您可以使用 gdb 检索回溯:gdb &lt;binary&gt; core,然后是 bt
  • l 不是split 的选项,请改用-l
  • 是的,你是对的,我已修复它,但它对我没有帮助。我遇到了同样的运行时错误

标签: c linux fork


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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 &lt;2 argv[1] 不存在,取消引用将导致未定义的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 2012-11-19
      • 1970-01-01
      • 2014-09-30
      • 2015-06-25
      相关资源
      最近更新 更多