Problem with simple circular list in C

Asked

Viewed 32 times

-2

I’m trying to make a circular list but whenever I compile this giving error. Could point me the error?

#include <stdio.h>
#include <stdlib.h>

typedef struct lista
{
    int info;
    struct lista *prox;
} lista;

lista* criarLista(void)
{
    return NULL;
}

lista* inserirListaFim(lista* l, int i)
{
    lista *novo = (lista*)malloc(sizeof(lista));
    novo->info = i;
    novo->prox = l;
    return novo;
}

int listaVazia(lista *l)
{
    if(l==NULL)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void imprimeLista(lista *l)
{
    lista *p = l;
    if(listaVazia(l))
    {
        printf("Lista Vazia!!!\n");
    }
    else
    {
        do
        {
            printf(" | %d |", p->info);
            p = p->prox;
        }
        while(p != l);
    }
}


int main()
{
    lista* l = (lista*)malloc(sizeof(lista));
    l = criarLista();
    l = inserirListaFim(l, 1);
    l = inserirListaFim(l, 4);
    l = inserirListaFim(l, 7);
    imprimeLista(l);
    return 0;
}
  • 1

    Which error message is reported by the compiler?

  • Process returned -1073741819 (0xC0000005)

  • I did the debugging and it’s in the instruction imprimeLista(l); that the system is stopping.

  • Yeah, the problem is I can’t get this part

1 answer

1


The first error is this malloc at the beginning that allocates the memory to the variable l and soon after you assign NULL for l with the function criarLista, leaking the memory.

Directly assign the function creatList to l:

lista* l = criarLista();

The second error is the instruction printf(" | %d |", p->info); of imprimeLista that dereference p without checking whether it is null or not.

Verique no while se p contains a value:

while(p && p != l);

  • Okay, what’s the best way to solve this problem?

  • @Guilhermebarbosa updated the answer with the solutions.

  • worked out here, thank you very much!

Browser other questions tagged

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