0

Can't understand why this segfault in c, valgrind said the fault is at line 25. It is a program to manage a medical studio, when e==1 a patient arrives so it must be added to the queue, e==2 a patient is visited so the first element in queue must be deleted, when e==0 the studio close and the program must print the list of patients remained in alphabetical order and the $.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN (101)

typedef struct _item {
  char *name;
  struct _item *next;
} item;

void insert(item* tail, item* next){
  item* new = (item*)malloc(sizeof(item));
  new->name = (char*)malloc(MAXLEN*sizeof(char));
  new->next = NULL;
  scanf("%s", new->name);
  if (tail == NULL){
    tail = new;
    next = tail;
  }
  else
    next->next = new;
}

void examination(item *tail){
  item *patient;
  if (tail->next == NULL)
    tail=NULL;
  else{
    patient = tail;
    tail = tail->next;
    free(patient);
  }
}

int cmp(const void *a, const void *b){
  return strcmp(*((char**)a) , *((char**)b));
}

int main(){
  int e=1, counter=0, i=0;
  item *tail = (item*)malloc(sizeof(item));
  item *next;
  char **remained;
  tail = NULL;
  next = tail;

  while (e != 0){
    scanf("%d", &e);
    switch (e){
    case 1:
      insert(tail, next);
      break;
    case 2:
      examination(tail);
    case 0:
      break;
    default:
      return 1;
    }
  } 
  next = tail;
  while (next != NULL){
    counter ++;
    next = next->next;
  }
  next = tail;
  remained = (char**)malloc(counter*sizeof(char*));
  while(i < counter){
    remained[i] = next->name;
     next = next->next;
    i++;
  }
  qsort(remained, counter, sizeof(item), cmp);
  next = tail;
  while (next != NULL){
    printf("%s\n", next->name);
    next = next->next;
  }
  printf("$\n");
  return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94

1 Answers1

2
if (tail->next == NULL)

The tail->next passed to examination() is uninitialized because insert() you are passing the pointer by value and not by reference nor returning the pointer from insert() so basically tail is allocated memory but the members are not initialized and you are trying to access them which will lead to undefined behavior and hence the crash.

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • @GrijeshChauhan As part of my answer I say `tail` members need to be initialized and also have given 2 ways to do it. One Have a pointer to pointer as a argument and another do all the operation within `insert()` and return a pointer of type `item` – Gopi Apr 02 '15 at 08:32