#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