【问题标题】:Is the File pointer causing segmentation fault in code [duplicate]文件指针是否导致代码中的分段错误[重复]
【发布时间】:2018-11-25 01:34:50
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <sys/types.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>

char date[35] = {"0"};

void main()
{
        FILE *fp;
        char ch;
        int i=0;

        if(fork() == 0)
        {
                system("date '+%Y-%m-%d %H:%M:%S' > date.txt");
                exit(0);
        }
        wait(0);

        fp = fopen("date.txt","w+");
        if(fp == 0) {return;}

        while((ch = fgetc(fp)) != EOF)
        {
                date[i++] = (char)ch;
        }
        fclose(fp);
        date[i] = '\0';

        printf("date = %s", date);
}

我一直在这段代码中遇到分段错误。 我什至尝试过手动创建名为“date.txt”的文件。

date '+%Y-%m-%d %H:%M:%S' &gt; date.txt 命令在 bash 上单独运行良好。

谁能帮我看看,我做错了什么?

[update:] 忘记初始化 i = 0。已编辑,但段违规仍然存在。

【问题讨论】:

  • 您应该检查 fp 是否 == 为 NULL,而不是 0
  • 这里date[i++] i 的价值是什么?你没有初始化i
  • ..int i = 0;
  • 'char ch;'永远不会是 EOF。
  • 如果将 char 更改为 int 解决了您的问题,您可以通过单击投票按钮下方的复选标记将答案标记为正确。 (这也会给你两个声望点)

标签: c linux segmentation-fault


【解决方案1】:

你应该初始化变量i,否则它会得到一个随机值。

void main()
{
    FILE *fp;
    char ch;
    int i = 0;
...
}

【讨论】:

  • 谢谢。愚蠢的错误。我初始化了 i = 0。但是,段违规仍然存在
  • 我没有遇到任何段错误,请尝试提供所需输出的示例
【解决方案2】:

语句溢出了最大大小 35。这意味着 i 变得大于 0..34。

date[i++] = (char)ch;

【讨论】:

    【解决方案3】:

    您正在使用 char 值来检查 EOF,但由于 EOF 是一个数值,因此 ch 永远不会等于 EOF。这意味着您的循环将永远运行,超出您的数组,该数组只有 35 个元素。您必须改用int ch

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 2021-03-02
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2015-06-20
      • 2013-07-26
      相关资源
      最近更新 更多