我正在研究链表实现。我需要使用clear()
函数删除一些动态内存,但它给了我一个错误:
对象0x100105400的malloc:***错误:释放的指针未分配
当我注释掉clear()
函数时,我的析构函数会给我同样的错误,但delete
在哪里。
从错误消息中,我想我删除了一个未分配的内存,但找不到。你认为我做错了什么?你有什么建议吗?
template <class T>
void LinkedList<T>::clear(){
node* temp = head;
while (temp != NULL){
head = head->next;
delete temp;
temp = head;
}
head = NULL;
tail = NULL;
size = 0;
}
template <typename T>
LinkedList<T>::~LinkedList(){
node* current = head;
while (head != NULL){
current = head->next;
delete head;
head = current;
}
size = 0;
}
下面是我的Flight.cpp文件:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <ostream>
#include <sstream>
#include <vector>
#include "Flight.h"
Flight::Flight(){
}
Flight::~Flight(){
LinkedList<LinkedList<ArrivalCity>>::node* temp = flightWeb.getNodeAtIndex(0);
while(temp != NULL){
temp->data.clear();
temp = temp->next;
}
flightWeb.clear();
}
void Flight::modifyCitiesLinkedList(ArrivalCity& city_1, ArrivalCity& city_2){
int position = 0;
//check if city1 existed. if yes, just add the object of arrival city to corresponding list. if no, create a new node to flightWeb and add object to corresponding list
if(startingCityRepeated(city_1.getName(), position) == true){
flightWeb.getNodeAtIndex(position)->data.addNode(city_1);
} else {
LinkedList<ArrivalCity>* newNode = new LinkedList<ArrivalCity>;
newNode->addNode(city_1, city_1.getName());
flightWeb.addNode(*newNode, city_1.getName());
}
position = 0;
//check if city2 existed. if yes, just add the object of arrival city to corresponding list. if no, create a new node to flightWeb and add object to corresponding list
if(startingCityRepeated(city_2.getName(), position) == true){
flightWeb.getNodeAtIndex(position)->data.addNode(city_2);
} else {
LinkedList<ArrivalCity>* newNode = new LinkedList<ArrivalCity>;
newNode->addNode(city_2, city_2.getName());
flightWeb.addNode(*newNode, city_2.getName());
}
}
//return false: no matching cities existed
//return true: found the matching city
bool Flight::startingCityRepeated(std::string city, int& position){
//no elements in the list, return false, no need to check
if(flightWeb.getSize() == 0){
return false;
}
LinkedList<LinkedList<ArrivalCity>>::node* temp = flightWeb.getNodeAtIndex(0);
while(temp != NULL){
//city node existed, return true;
if(temp->name == city){
return true;
}
temp = temp->next;
position++;
}
//no matching name found, return false
return false;
}
int main(int argc, const char* argv[]) {
Flight flight;
flight.readFlightRoute(argc, argv);
//flight.printStartingCities();
//flight.printArrivalCities();
//flight.totalAvailableFlight();
return 0;
}
您注释掉clear()
函数的事实并不能告诉我们什么;要么你真正注释掉的是clear()
的所有调用,要么你实际上注释掉了clear()
,这意味着clear()
没有从你的代码中调用(否则你的程序将不再编译),注释掉一个没有调用的函数没有任何作用。
以下内容:
while (current != NULL)
while (head != NULL){
是两个(严重缩进的)嵌套循环,不可能是您想要做的
如果没有一个完整的、自包含的、可运行的示例,很难判断,但可能会发生的情况是,内部循环的第一次执行将清除您的列表,然后外部循环将再次迭代,current
和head
都指向最后一个节点,该节点已被释放,从而导致错误。
不需要所有这些复杂的东西,只需从析构函数中调用clear()
即可。