简体   繁体   中英

Problem deleting a node in my doubly linked list

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
    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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM