I am getting a “Segmentation fault (core dumped)” run-time error with the following code:
#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;
}
I have narrowed the error down to the delete list; lines (or whichever one comes first). I am just wondering as to why this is and how to possibly fix it. Any insight on this matter would be useful.
You have two problems that I can see.
First, in this loop:
You are creating a bunch of dynamic
Students and putting the latest one inxand the previous one is lost. This creates 100Students dynamically and 99 of them are leaked. Also it doesn’t fill an array withStudents like the comment above it says it does. I’m not sure what you’re trying to do here so I can’t comment on what you need to do instead.Secondly, you are calling
deletehere:on
Students that are in automatic storage (the stack) (because you filled the list with pointers to theStudents increatewhich holds automaticStudents), which leads to undefined behaviour and is probably the cause of your segfault. You don’t need to deallocate theseStudents because they will be deallocated when the array goes out of scope at the end ofmain.