Problem with repeated number removal algorithm on doubly chained list

Asked

Viewed 70 times

1

Could someone help me with the following code?

void removeRepetidos(Lista *l)
{

    Elemento *aux = (*l);
    Elemento *aux2;
    Elemento *aux3;

    while(aux!=NULL)
    {
        aux2 = aux->prox;

        while(aux2 != NULL)
        {
            if(aux->num == aux2->num)
            {

                aux2->ant->prox = aux2->prox;

                if(aux2->prox!=NULL)
                {
                    aux2->prox->ant = aux2->ant;
                }


                aux3 = aux2;

            }


            aux2 = aux2->prox;
            free(aux3);
        }

        aux = aux->prox;
    }
}

He is crashing while executing, by removing the relocation function free() the program works perfectly. I did not find any error in the logic of my code, I did several table tests.

1 answer

2


The aux3 pointer is being deleted twice,

void removeRepetidos(Lista *l)
{
  Elemento *aux = (*l);
  Elemento *aux2;
  Elemento *aux3;

  while (aux!=NULL)
  {
    aux2 = aux->prox;
    while (aux2 != NULL)
    {
      if (aux->num == aux2->num)
      {
        aux2->ant->prox = aux2->prox;
        if (aux2->prox != NULL)
        {
          aux2->prox->ant = aux2->ant;
        }

        aux3 = aux2;
        aux2 = aux2->prox; // <---
        free(aux3);        // <--- incluir aqui
        continue;          // <---
      }

      aux2 = aux2->prox;
      // free(aux3); // <--- tirar daqui
    }

    aux = aux->prox;
  }

}

  • 1

    But if I release the aux3 before the increment aux2 = aux2 -> prox no problem? even if the aux3 pointer receives the aux2?

  • see the new edition

Browser other questions tagged

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