简体   繁体   中英

Seg fault during fgets?

Here's my code:

    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");
    }

All those printfs are just to locate where the segfault takes place. The input file is 100 lines long, and this function works 15 times, completes all the checks, and then seg faults before "backin!" is printed on the 16th iteration.

I looked through the input file and there's nothing fishy about it (definitely fewer than 1000 characters), seems like there's just an issue with fgets but I don't know what.

Make sure that the size of line is at least 1000 chars or change your code as:

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

You need to have your line large enough to hold the longest line or have a logic to process partial lines.

you can try using fscanf with the help of regular expression "%[^\\n]s" . this will accept all your tokens till end of line character.

  • Irrelavant to the question but still, practice using getch() after printf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM