Hi all,

I'm writing a program to read from a stream file, one line at a time,
I used getline() and fgets(), both gives a correct result,
but they give a "segmentation fault" when reading the last line of the file, I think because of the NULL character at the end of the file.
do they supposed to give such an error when reading a NULL character?
and what are other alternatives that could work for my code?
I'm using Ubuntu.

thanks in advance,

segmentation fault results from trying to read/write from/to an invalid address..

Here's what happens when fgets() encounters the end of file or an error...Quote from my man files

"char *fgets(char *s, int size, FILE *stream);

gets() and fgets() return s on success, and NULL on error or when end
of file occurs while no characters have been read."

Could you post your code so we could have a look at it.

Edited 6 Years Ago by gerard4143: n/a

here it is: (This is one function I call it to read one tuple (i.e. line) from the file)

OrderTupleType ReadOrder(FILE* fp, bool &finished)
{
     char * result;
     OrderTupleType RealOrderTuple;
     TupleType CharOrderTuple;
     fgets(CharOrderTuple, sizeof(CharOrderTuple), fp);
     if(feof(fp))
          finished = true;
     else
          finished = false;

     result = strtok(CharOrderTuple, "|");
     RealOrderTuple.OrderKey = atoi(result);
     result = strtok(NULL, "|");
     result = strtok(NULL, "|");
     result = strtok(NULL, "|");
     result = strtok(NULL, "|");
     RealOrderTuple.OrderDate = result;

     return RealOrderTuple;
}

thanks,

Edited 6 Years Ago by majood: n/a

For debugging purposes I would set up a char buffer the size of CharOrderTuple and read the file into it. Then take the strlen of it and see if it is the correct length. If it is, copy it over to CharOrderTuple with memcpy. If it's too short, I'm guessing that's your seg fault. Test for good input and only do the strtok calls if the test passes.

Lines 7 - 10 might be sufficient too, but you don't check the finished variable prior to doing the strtok, so maybe you are parsing an empty line. Read a line from the file, test for valid input, and parse only if the test passes.

This article has been dead for over six months. Start a new discussion instead.