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