Search code examples
cfile-iofilesegmentation-faultstructure

Reading data from a binary file and storing it in a structure yields a segmentation fault


I'm having problems with a 'segmentation fault' error.

I'm reading data from a binary file, which I'm trying to store in a structure; here's the code to what I'm doing or 'trying' to do:

struct Medico //users are medics
{
  int Id_Doctor; //Id User
  int Estado; //status of the user
  char Nombre[60]; //name of the user
  char Clave_Acceso[20]; //password of the user
  char Especialidad[40]; //especialty of the user
  struct Medico *next;
};

void Cargar_Datos () //load files
{
  FILE *Archivaldo; ///file- Archivo means file
  struct Medico * head = NULL;
  struct Medico * prev, *current;
  char especialida[40], password[20]; ///locals for specialty and password
  char nombre_doc[60]; ///local for name
  int estado_doc, id_doc; // local for status 

  if((Archivaldo=fopen("md.dat", "a+b"))==NULL)
    {
      printf("No se pudo abrir el archivo de Medicos\n");
      exit(1);
    }
  rewind(Archivaldo);
  current = (struct Medico *) malloc (sizeof(struct Medico));

  fread(&id_doc, sizeof(int), 1, Archivaldo);
  fread(nombre_doc, sizeof(char), sizeof(nombre_doc), Archivaldo);
  fread(password, sizeof(char), 20 , Archivaldo);
  fread(especialida, sizeof(char), 40, Archivaldo);
  fread(&estado_doc, sizeof(int), 1, Archivaldo);

  printf("ID: %d\n", id_doc);
  printf("\nDoctor: ");
  puts(nombre_doc);
  printf("\nPassword: ");
  puts(password);
  printf("\nEspecialidad: ");
  puts(especialida);
  printf("\nEstado: ");
  if(estado_doc==1)
    puts("Activo\n");
  else
    puts("Inactivo\n");
  current->Id_Doctor=id_doc;
  strcpy(current->Nombre, nombre_doc); 
  strcpy(current->Clave_Acceso, password); 
  strcpy(current->Especialidad, especialida);
  current->Estado=estado_doc; 
  current=current->next;

  fclose(Archivaldo);

}

Solution

  • The best way to debug a segmentation fault is to use a debugger such as GDB or a memory analyser such as Valgrind.

    If one is not available, it usually helps to add numbered printf() statements in the code. When you find the last printf() that was executed before the error, you can add more printf() statements and repeat your tests to narrow it down.

    A few common causes of a segmentation fault in C program:

    • Trying to dereference a NULL pointer. That often happens if said pointer is the result of a function call such as malloc() or fopen(), whose output was not checked for errors before proceeding.

    • Going beyond the edges of an array or allocated block. Strings that are not null-terminated properly are a common cause of this. If printing a string produces garbage in the screen, this could be the cause.

    • Trying to use a memory block that has already been freed with free().