我正在尝试删除单个循环链表中的所有节点。但我得到了以下错误:
malloc: *** error for object 0x1005068f0: pointer being freed was not allocated
以下是功能:
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--;
}
}
我在这一行上收到错误:
delete traversePointer;
我的问题是为什么traversePointer没有在while循环中分配,如错误所示?
答案 0 :(得分:0)
应该是:
while(this->size){
当循环完成时,然后设置this-> head = nullptr。没有必要在循环中设置traversePoitner = nullptr。
替代版本(我还没有确认这一点),这并不依赖于此 - >大小正确,只是列表是循环的:
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;
}