Chained lists – add at the bottom of the list

Posted on

Question :

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 {
    return false;



Answer :

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


Leave a Reply

Your email address will not be published. Required fields are marked *