Program stops responding when I try to fill the list

Asked

Viewed 32 times

1

This is the code, it simply reads the values and puts it on the list, but in the last loop it stops responding

#include<stdio.h>
#include<stdlib.h>
typedef struct pessoa {
    int horas,minutos;
    int conversao;
    int atendimento;
    int critico;
    int horacritica;
    int horasair;
    struct pessoa *proximo;
}paciente;

paciente *cabeca;
paciente *auxiliar;
paciente *anterior;

void insere(paciente *cabeca){
    paciente *elemento =(paciente*)malloc(sizeof(paciente));


    scanf("%d %d",&elemento->horas,&elemento->minutos);

    scanf("%d",&elemento->critico);

    if(cabeca->proximo == NULL){
        cabeca->proximo = elemento;
    } else {
        auxiliar->proximo = cabeca;
        while(auxiliar->proximo != NULL){
            auxiliar = auxiliar->proximo;
        }
        auxiliar->proximo = elemento;
    }


}

int main(){
    int N,cout;
    cabeca = (paciente*)malloc(sizeof(paciente));
    cabeca->proximo = NULL;

    printf(" QUANTOS NOS QUER : ");
    scanf("%d",&N);
    for(cout=1;cout<=N;cout++){
        insere(cabeca);
    }


    return 0;
}
  • Put some printf we strategically position to know what is happening

  • I noticed that when I invoked insere, you are not initiating the value of elemento->proximo, this can lead to complications. Initialize this value, it may help to avoid an infinite loop in the while (auxiliar->proximo != NULL)

  • The problem is that always when it arrives at the last loop the algorithm stops responding and error. Like, he doesn’t even read all the figures and the IDE hangs here D:

  • Make my two suggestions from previous comments. If not resolved, you will be closer to the answer

  • It worked. A doubt here, there is a difference between doing this : auxiliary = auxiliary->proximo and auxiliary->proximo = auxiliary->proximo ?

  • there is a lot of difference yes. The second form is a tautology. Basically you are doing var = var in this second way, which is the same thing as doing nothing. Maybe you still fall into an illegal access memory, which would cause a segmentation fault. For example of auxiliar->auxiliar be worth NULL

  • I will formalize the comment just for questions to have the question answered

Show 2 more comments

1 answer

0


You are not initiating the value of elemento->proximo in function insere.

Put elemento->proximo = NULL shortly after the malloc already solves your problem.

Another alternative would be using calloc, making a clean allocation (all bytes start with 0).

  • Thanks, Brow. I got it here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.