我正在学习使用链表实现Stack。这是节点类:
class StudentInfo {
public:
string id, name, course;
double GPA;
StudentInfo *next;
};
这是Stack类:
class StackLinkedList {
public:
StudentInfo* top; //pointer to point to the top node
int size; //variable to keep the size of the stack
//constructor
StackLinkedList() {
this->size = 0;
this->top = NULL;
}
//destructor
~StackLinkedList() {
StudentInfo *current = top;
while (top) {
current = current->next;
delete top;
top = current;
}
}
//to add item into stack - push on top
void push(StudentInfo *newStudent) {
if (!top) {
top = newStudent;
return;
}
newStudent->next = top;
top = newStudent;
size++;
}
void main() {
StudentInfo s1("phi", "123", "computer science", 4.0);
StudentInfo s2("abc", "123", "software engineer", 4.0);
StudentInfo s3("zxc", "123", "business management", 4.0);
StackLinkedList list;
StudentInfo *ptr;
ptr = &s1;
list.push(ptr);
ptr = &s2;
list.push(ptr);
ptr = &s3;
list.push(ptr);
};
当我尝试在push()和printAll()上运行单元测试时,一切正常。但是,在调用destructor()并显示错误后,调试断言失败…is_block_type_valid(header-> _block_use)。调试器在以下位置触发了一个断点delete top;
//destructor
~StackLinkedList() {
StudentInfo *current = top;
while (top) {
current = current->next;
delete top; //here
top = current;
}
}
如果我放在top = NULL;
前面delete top;
,错误就消失了。因此,我对该top = NULL;
声明有些困惑。编辑:NodeType的构造方法
StudentInfo(string id, string name, string course, double gpa) {
this->id = id; this->name = name; this->course = course; this->GPA = gpa; this->next = NULL;
}
您通过尝试访问delete
具有自动存储期限的对象来调用“未定义行为” 。
int main() {
StudentInfo s1("phi", "123", "computer science", 4.0);
StudentInfo s2("abc", "123", "software engineer", 4.0);
StudentInfo s3("zxc", "123", "business management", 4.0);
StackLinkedList list;
StudentInfo *ptr;
ptr = &s1;
list.push(ptr);
ptr = &s2;
list.push(ptr);
ptr = &s3;
list.push(ptr);
};
正如可以看到,s1
,s2
,s3
是对象自动存储持续时间(又名,编译器自动在它们的寿命结束调用其析构函数)。
然而,你通过他们的地址list
,他们的析构函数deletes
的链表细节中的所有指针,一旦破坏....不要调用delete
一个指针,没有使用创建的对象new
。
一些附加说明:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句