I've written two classes: Student and Course. The Course class has a Student *students as a data member in its body. In my top class StudentReviewSystem, I have a Course *courses as a data member, and I have a deleteCourse(const int courseId) method which deletes the course with "courseId and resizes "courses". Here is my code of deleteCourse method:
void StudentReviewSystem::deleteCourse(const int courseId){
int index = 0;
bool found = false;
//temp arr
Course *temp = new Course[courseSize];
for(int i = 0; i < courseSize && !found; i++){
if(courseId == courses[i].getCourseId()){
index = i;
found = true;
}
}
if(found){
temp = courses;
courses = new Course[courseSize-1];
for(int i = 0; i <= index-1;i++ ){
courses[i] = temp[i];
}
for(int i = index+1; i < courseSize; i++){
courses[i-1] = temp[i];
}
delete[] temp;
cout << "Course has been deleted!" << endl;
courseSize--;
}
}
When I try to delete temp, I get a "glibc detected" error with a memory map under it and at the then aborted(core dumped) error. But when I comment out the line delete[] temp; , it works. Can you help me, I'm really new to C++.
Thank you...
P.S: When I comment out the ~Course(){ delete[] students;} destructor, it again works. I think I have a really silly problem, thank you again...
Course *temp = new Course[courseSize];is always abandon and leaked in this code. This isn't Java. And by the looks of it yourCourseclass isn't practicing theRule of Threeat all.std::vectoror some other standard container, and use smart pointers and standard algorithms - you could reduce that function to about three lines that don't contain raw news or deletes. You're leaking aCourse[courseSize]there. I suspect you're double-deleting students if they can belong to several courses.