Chained lists - add at the bottom of the list

3

To have problem at the time of executing this code, whose objective is to add an element at the end of the list, the program is waiting for something that I do not know what it is, then the program of the error. Any light?

To start now lists, then the possibility of being a beast error is big hehe.

typedef struct evento_t {
double tempo;
char descricao[50];
int id_origem, id_destino;
struct evento_t *prox;
} evento_t;


bool eventos_adicionar_fim (evento_t **lista, double tempo, char descricao[], int   id_origem, int id_destino) {

evento_t *novoelemento = (evento_t*)malloc(sizeof(evento_t));
evento_t *auxiliar = *lista, *anterior = NULL;

if (novoelemento!=NULL) {
    novoelemento->tempo = tempo;
    strcpy (novoelemento->descricao, descricao);
    novoelemento->id_origem = id_origem;
    novoelemento->id_destino = id_destino;
    novoelemento->prox = NULL;

    while (auxiliar!=NULL) {
        anterior = auxiliar;
        auxiliar = auxiliar->prox;
    }

    anterior->prox = novoelemento;

    return true;
}

else {
    exit(1);
    return false;
}

}

    
asked by anonymous 28.02.2014 / 00:23

1 answer

2

The problem is trying to insert something at the end of an empty list. In this case both the auxiliar and the anterior are NULL . The crash will happen when doing anterior->prox = novoelemento; . Instead add a check:

if (*lista == NULL) {
    *lista = novoelemento;
} else {
    // código anterior
}
    
28.02.2014 / 01:05