Search code examples
csegmentation-faultfeof

Why a segmentation fault in feof()?


I have the following enum and struct:

enum Destination { unknown = 0, hosok, parlament, var };

struct Client
{
  char name[30];
  char email[30];
  char phone_num[11];
  int client_num;
  enum Destination destination;
  struct tm registration_date;
};

When I invoke the following method, it reads the first struct and print it's name, then I get a segmentation fault.

void list_clientss()
{
  FILE *f = fopen(filename, "r");
  if( f == NULL )
  {
    perror("Error");
  }
  struct Client client;
  while( !feof( f ) )
  {
    fread(&client, sizeof(struct Client), sizeof(struct Client), f);
    printf("Name: %s\n", client.name);
  }
  fclose(f);
}

What did I wrong?


Solution

  • Firstly, your fread calls should be as follows:

    fread(&client, sizeof(struct Client), 1, f);
    

    Secondly, instead of using feof, you might use the return value of fread. fread returns the number of elements to read that you have passed to it. You can check if this number is different than one. For example,

    while (fread(&client, sizeof(struct Client), 1, f) == 1) {
        printf("Name: %s\n", client.name);
    }
    

    Edit 1: Update the while loop to more idiomatic and elegant version as Weather Vane suggested.