【发布时间】:2012-11-16 03:58:24
【问题描述】:
这是我的代码:
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!" 之前 seg faults在第 16 次迭代时打印。
我查看了输入文件,没有任何可疑之处(肯定少于 1000 个字符),似乎 fgets 有问题,但我不知道是什么。
【问题讨论】:
-
检查您之前提出的问题并接受您认为好的答案
-
line是如何定义的?它是否足够容纳 1000 个字符? -
哇,原来如此。 Line 包含 21 个字符,这条线看起来像 21,但我猜出于某种原因它是 22。将其更改为 30 并且可以正常工作。谢谢。顺便说一句,我能以某种方式接受这个答案吗?
-
不,那是评论,不是答案。如果@MichaelSh 添加了答案,那么您可以接受……您是否更改了行以容纳 30 个字符但仍尝试读取 1000?这会破坏 fgets 的长度参数的目的。
-
我很好奇 - 你认为
1000参数的含义是什么?
标签: c segmentation-fault fgets