vendredi 8 mai 2015

malloc can't create space for struct in queue

I tried to create a queue which contains 2 int values. The problem happens in insert function. When i try to allocate memory for head->front->next program halts. The error happens only in else part in insert function.

struct Patient{
   int national_id;
   int condition;
};

struct Node{
   struct Patient *info;
   struct Node *next;
};

struct Queue{
   int total;
   struct Node *rear;
   struct Node *front;
   int insert_number;
};

void insert (struct Queue *head, int natid, int cond);
void pop_min(struct Queue *head);
struct Queue *create_queue(void);
void destroy_queue(struct Queue *head);
void read_file(struct Queue *head);
void print_natid(struct Node *node);
void pop_all_elements(struct Queue *head);

void main(){
   struct Queue *head;

   head=create_queue();
   read_file(head);
   pop_all_elements(head);
   destroy_queue(head);
}

struct Queue *create_queue(void){

   struct Queue *head =(struct Queue*) malloc(sizeof(struct Queue));
   head->total=0;
   head->insert_number=0;
   return head;

}

void print_natid(struct Node *node){
   printf("%d ",node->info->national_id);
}


void insert (struct Queue *head,int natid, int cond){

   if(head->total==0){
      head->front=(struct Node*)malloc(sizeof(struct Node));
      head->front->info->national_id=natid;
      head->front->info->condition=cond;
      head->rear=head->front;
   }
   else{

      head->front->next=(struct Node*)malloc(sizeof(struct Node));
      head->front->next->info->national_id=natid;
      head->front->next->info->condition=cond;
      head->front=head->front->next;
   }


   head->insert_number++;
   head->total++;

   if(head->insert_number==3){
      pop_min(head);
      head->insert_number=0;
   }

   print_natid(head->rear);

}

void pop_min(struct Queue *head){

   printf("%d ",head->rear->info->national_id);

   struct Node *temp=head->rear;
   head->rear=head->rear->next;

   free(head->rear);
   free(temp);
}

void destroy_queue(struct Queue *head){
   free(head);
}

void pop_all_elements(struct Queue *head){
   struct Node *temp;

   while(head->rear!=head->front){
      print_natid(head->rear);
      temp=head->rear;
      free(temp);
      head->rear=head->rear->next;
   }

   print_natid(head->rear);
   free(head->rear);

}

void read_file(struct Queue *head){
   FILE *fp;
   int natid;
   int cond;
   fp=fopen("patients.txt","r");

   while (fscanf(fp,"%d %d", &natid, &cond) ==2)
      insert(head,natid,cond);

   fclose(fp);
}

Aucun commentaire:

Enregistrer un commentaire