程序运行并且测试成功,但是在列表和测试结果之间我得到了:assignment_2.2(10729,0x7fff78db0300)malloc: *对象0x7fb132d00000的错误:被释放的指针不是分配 * 在malloc_error_break中设置断点以进行调试 知道如何解决这个问题吗?
的main.cpp
#include "OLinkedList.h"
using namespace std;
int main(int argc, char** argv) {
OLinkedList CircleList;
CircleList.fillList(0);
CircleList.prntList();
CircleList.OTest();
return 0;
}
OLinkedList.h
#ifndef OLINKEDLIST_H
#define OLINKEDLIST_H
#include <iostream>
#include <iomanip>
using namespace std;
class OLinkedList{
private: struct Link{
int data;
Link *next;
};
Link *head;
Link *tail;
public: OLinkedList(){head = nullptr; tail = nullptr;};
~OLinkedList();
void fillList(int);
void prntList();
void OTest();
};
//Destructor for Class used to delete memory of list
OLinkedList::~OLinkedList(){
Link *linkPtr = head;
Link *nextPtr;
//traverses to the end of the list to delete memory
do
{
nextPtr = linkPtr->next;
delete linkPtr;
linkPtr = nextPtr;
}while(linkPtr!= nullptr);
}
//
void OLinkedList::fillList(int size){
Link *front = new Link; //create first link
head = front; //set first link = to traversal
head->data = size++; //Fill the front with data
head->next = nullptr; //Point the front to no where
Link *temp = head;
do{
Link *end = new Link; //Create a new link
end->data = size++; //Fill with data
end->next = nullptr; //Point to no where
temp->next=end;//Previous link will point to the end
temp=end; //Now this has become previous link
tail = end;
tail->next = head;
}while(size < 10); //Repeat until filled
}
void OLinkedList::prntList(){
Link *linkPtr;
linkPtr = head;
int i = 0;
do{
cout<<" "<<setprecision(3)<<linkPtr->data;
linkPtr = linkPtr->next;
i++;
}while(i < 10);
}
//Used to prove list is circular
void OLinkedList::OTest(){
Link *linkPtr = tail->next;
cout<<"\nAfter "<<tail->data<<" is "<<linkPtr->data;
}
#endif /* OLINKEDLIST_H */
答案 0 :(得分:0)
当您在head旁边设置tail-&gt;时,您将按预期创建循环链接列表。你的do while循环应检查linkPtr!= head,而不是nullptr,因为你正在进行双重自由。这是因为删除指针并不会使之前指向它的任何变量无效,因此您的循环最终会返回到头部。
事实上,如果不是双重免费,你的代码将进入无限循环。