【问题标题】:Segmentation Fault in fgets()fgets() 中的分段错误
【发布时间】:2014-12-07 23:06:54
【问题描述】:

我在 fgets 上遇到了段错误。
我在之前和之后使用 printf 进行了测试,它在哪里停止(在 while 循环之前的 main 方法中)。
具有讽刺意味的是,我有另一个程序可以执行相同的调用并且可以正常工作。
这是我的代码:

child(char * input){
    shrink(input);

    char ** words;
    char * word = strsep(&input, " ");
    int spaces = 0;

    while (word != NULL){
        words = realloc(words, ++spaces);

        if (words == NULL){ /* memory allocation failed */
            exit (1);
        }

        words[spaces-1] = word;
     word = strsep(&input, " ");
    }

    words = realloc (words, ++spaces);
    words[spaces] = NULL;

    char str[105];
    strcpy(str, "/bin/");
    strcat(str, words[1]);
    shrink(str);
    execvp(str, words);
    exit(0);

}

main() {

    char * input;
    int pid;

    printf("$ ");
    fgets(input, 100, stdin);

    while (strncmp(input, "exit", 4)){  /* while exit command has not been entered */
        pid = fork();
        if(pid == 0){           /* child process */
            child(input);
        }
        else if(pid < 0){       /* error while doing fork */
            exit(1);
        }
        else{                   /* parent process */
            wait(0);
        }

        printf("$ ");
        fgets(input, 100, stdin);
    }

    exit(0);

}

(shrink 方法从输入中取出\n)

【问题讨论】:

  • 你需要为input分配内存,现在你告诉 fputs() 将读取的数据存储到内存中的随机位置...
  • char * input; 更改为char * input = (char *)malloc(101); 应该已经有所帮助...
  • char ** words; uninitialised: realloc() 会做一些讨厌的事情。
  • @HartmutHolzgraefe:虽然这在许多实现中实际发生,情况更糟:只是读取未初始化的无记忆变量是UB.

标签: c segmentation-fault fgets


【解决方案1】:

您还没有为input 分配任何内存,即它还没有被初始化。 它持有的地址是随机的,很可能指向不可写的内存区域(例如 NULL),这就是存在分段错误的原因。

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多