-1

I am doing a doubly linked list and I am doing the pop_front function. I am having some issues deleting the nodes when there is only one node in the list.

int main()
{
    ForwardList<int> l;
    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    l.push_back(4);
    l.push_back(5);

    l.pop_front();
    l.pop_front();
    l.pop_front();
    l.pop_front();
    l.pop_front();
}
void pop_front()
{
    if (!empty())
    {
        if (this->head == this->tail)
        {
            delete this->head;
            delete this->tail;
            this->head = nullptr;
            this->tail = nullptr;
        }
        else
        {
            this->head = this->head->next;
            delete this->head->prev;
            this->head->prev = nullptr;
        }
    }
}

I am getting this error:

a.out(69846,0x10d5105c0) malloc: *** error for object 0x7fa7a2c02b50: pointer being freed was not allocated
a.out(69846,0x10d5105c0) malloc: *** set a breakpoint in malloc_error_break to debug
[1]    69846 abort      ./a.out
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Miguel Yurivilca
  • 375
  • 5
  • 12

2 Answers2

3
    if (this->head == this->tail)
    {
        delete this->head;
        delete this->tail;
        this->head = nullptr;
        this->tail = nullptr;
    }

Look at these lines, since this->head == this->tail, delele this->head and delete this->tail are deleting same pointer twice.

duyue
  • 759
  • 5
  • 12
0

In addition to @duyue answer, a better design is to split node unlinking and disposal into separate functions. See example here.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271