#include <iostream>
#include "Student.h"
#include "SortedList.h"
using namespace std;
#define BOUNDS 100
int main() {
SortedList *list = new SortedList(); // points to the sorted list object
Student *create[BOUNDS]; // array to hold 100 student objects
int num = 100000; // holds different ID numbers
// fills an array with 100 students of various ID numbers
for (int i = 0; i < BOUNDS; i++) {
create[i] = new Student(num);
num += 10;
}
// insert all students into the sorted list
for (int i = 0; i < BOUNDS; i++)
list->insert(create[i]);
// removes each student from the list
num = 100000;
for (int i = 0; i < BOUNDS; i++) {
list->remove(num);
num += 10;
}
delete list;
return 0;
}
我得到一个seg错误与以前的代码。任何有关为什么这是或如何可能解决它的见解将不胜感激。赛格故障肯定是由delete list;
线造成分段错误C++
更新1:这是我的排序列表析构函数
/*
* Destructs this sorted list object
*/
SortedList::~SortedList() {
freeList(head);
}
/*
* Traverses throught the linked list and deallocates each node
*/
void SortedList::freeList(Listnode *L) {
Listnode *tmp = L; //holds the node to be deleted
//traverses the list
while (tmp != NULL) {
Listnode *next = tmp->next; //holds the value of the next node
//delete previous node
delete tmp->student;
delete tmp->next;
delete tmp;
//sets the next node to the node to be deleted
tmp = next;
}
//delete header node
delete L;
}
'delete list'应该调用'〜SortedList()',那么析构函数做什么都不平凡? – 2012-04-12 02:42:23
我会在一分钟后发布SortedList析构函数,如果你关心它的话。 – 2012-04-12 02:44:21
所以一个修正是从'SortedList :: freeList'中删除'delete tmp-> next;'行。是否SortedList拥有所有交给它的存储?如果它不拥有'student'指向的空间,那么'delete tmp-> student;'可能不正确。目前还不清楚SortedList :: remove的作用。这会删除ListNode,还是删除ListNode并删除'student'成员?如果它也删除'student'成员,那么它将与'SortedList :: freeList'一致,否则它不会。 – gbulmer 2012-04-12 03:44:33