c - fget 期间出现段错误?

标签 c segmentation-fault fgets

这是我的代码:

    while (fgets(line, 1000, fp) != NULL) 
    { 
      printf("backin!");
      if ((result = strtok(line,delims)) == NULL)
        printf("Need from_id, to_id, and distance on each line of input file.\n");
      else
        from_id = atoi(result);
      printf("check!\n");
      if ((result = strtok(NULL,delims)) == NULL)
        printf("Need from_id, to_id, and distance on each line of input file.\n");
      else
        to_id = atoi(result);
      printf("check!\n");
      if ((result = strtok(NULL,delims)) == NULL)
        printf("Need from_id, to_id, and distance on each line of input file.\n");
      else
        distance = atof(result);
      printf("check!\n");
      printf("from_id: %d, to_id: %d, distance: %f",from_id, to_id, distance);
      if(BuildGraph(graph_array, from_id, to_id, distance) == -1)
        printf("Error while filling in graph type"); 
      printf("check!\n");
    }

所有这些 printfs 只是为了定位段错误发生的位置。输入文件有 100 行长,这个函数运行 15 次,完成所有检查,然后在“backin!”之前进行段错误。在第 16 次迭代时打印。

我查看了输入文件,没有什么可疑的地方(肯定少于 1000 个字符),似乎只是 fgets 有问题,但我不知道是什么。

最佳答案

确保的大小至少为 1000 个字符,或将代码更改为:

while (fgets(line, sizeof(line), fp) != NULL) 
...

您需要让您的足够大以容纳最长的行或具有处理部分行的逻辑。

关于c - fget 期间出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13410167/

相关文章:

c - UI 凭证弹出窗口隐藏在服务窗口后面

foxpro - 如何将光标的数据写入txt文件中?视觉狐狸专业版

linux - fgets 不以换行符终止

c - c 中 fgets 使用错误

c++ - Bison:$$ 和 $1 指向相同的内存位置(两种指针类型的 union YYSTYPE)

c - sys_readlink 失败 EFAULT - 备选方案

c - 使用 C 分割 wav 文件

c - 调用 free() 时出现段错误

c++ - 从 vector C++ 中删除对象时出现段错误

python - Py_Finalize() 导致 Python 3.9 的段错误但不是 Python 2.7