Search code examples
c++linked-listcircular-list

C++ Circular Link List - remove all nodes


I am trying to remove all the nodes in singly circular linked list. But I got following Error:

malloc: *** error for object 0x1005068f0: pointer being freed was not allocated 

Following is the function:

void StudentLinkList::removeAll() {
    StudentData *traversePointer = this->head;

    while (this->head != nullptr) {
        this->head = this->head->getNext();
        delete traversePointer;
        traversePointer = nullptr;
        traversePointer = this->head;
        this->size--;
    }
}

I get error on this line:

delete traversePointer;

My question is that why traversePointer not allocated in while loop as shown in the error?


Solution

  • The while should be:

        while(this->size){
    

    When the loop completes, then set this->head = nullptr. There's no need to set traversePoitner = nullptr in the loop.

    Alternative version (I haven't confirmed this yet), that doesn't rely on this->size being correct, only that the list is circular:

    void StudentLinkList::removeAll() {
        if(this->head == nullptr)
            return;
        StudentData *traversePointer = this->head;
        StudentData *deletePointer;
        do{
            deletePointer = traversePointer;
            traversePointer = traversePointer->getNext();
            delete deletePointer;
        }while(traversePointer != this->head);
        this->head = nullptr;
        this->size = 0;
    }