[英]Segmentation Fault C++
我收到以下代码的“段错误(核心已转储)”运行时错误:
#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]);
// individually deletes each student
num = 100000;
for (int i = 0; i < BOUNDS; i++) {
delete list->find(num);
num += 10;
}
// insert all students into the sorted list
for (int i = 0; i < BOUNDS; i++)
list->insert(create[i]);
num = 100000;
for (int i = 0; i < BOUNDS; i++) {
list->remove(num);
num += 10;
}
cout << "test2" << endl;
delete list;
return 0;
}
我已将错误缩小到delete list;
行(或先到者)。 我只是想知道为什么会这样以及如何解决它。 关于此事的任何见解将是有用的。
我有两个问题。
首先,在此循环中:
for (int i = 0; i < BOUNDS; i++) {
x = new Student(num);
num += 10;
}
您正在创建一堆动态Student
,并将最新的Student
放入x
,而前一个则丢失。 这将动态创建100个Student
,其中99个被泄漏。 而且它不会像上面的注释那样用Student
填充数组。 我不确定您要在这里做什么,所以我无法评论您需要做什么。
其次,您在此处调用delete
:
delete list->find(num);
对Student
S中的自动存储(栈)(因为你使用指针充满名单到Student
■在create
持有自动Student
S),这会导致不确定的行为,很可能是你的段错误的原因。 您不需要取消分配这些Student
因为当数组在main
的末尾超出范围时,它们将被重新分配。
您肯定是在泄漏内存:
// fills an array with 100 students of various ID numbers
for (int i = 0; i < BOUNDS; i++) {
x = new Student(num);
num += 10;
}
x
在此代码段中泄漏,除非Student
的ctor以某种方式神奇地将其自身插入可以跟踪指针的位置。
这可能与崩溃有关。
不知道StudentList
是如何实现的,这是在黑暗中拍摄的,但是...
list->insert(&create[i]);
正在将堆栈分配的对象添加到列表,然后delete list->find(num);
尝试删除此堆栈分配的对象。 您不能delete
堆栈分配的对象。
除此之外,您的第一个for
循环正在泄漏内存。
我一直忍者。
这行有问题:
list->insert(&create[i]);
到那时,已经分配了create
,但是没有放入任何内容。 可能x = new Student(num)
应该在那里分配。
“创建”数组在堆栈上分配。 您正在尝试删除堆栈分配的内存,这就是您收到此错误的原因。
删除列表->查找(数字);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.