Home > Net >  Why does the value in classRosterArray seemingly persist after I delete in the 'remove' fu
Why does the value in classRosterArray seemingly persist after I delete in the 'remove' fu

Time:12-10

in Main.cpp I call the add function which adds student objects to classRosterArray

roster.add(id, firstName, lastName, email, age, daysInCourse1, daysInCourse2, daysInCourse3, degree);
roster.remove("A3");

Relevant part of add function in Roster.cpp:

Student* student = new Student(studentID, firstName, lastName, emailAddress, age, degreeprogram, daysInCourses);

classRosterArray[numberOfStudentsAdded] = student;

In the 'remove' function a studentID is passed in. If it matches a studentId in classRosterArray then that value is deleted:

void Roster::remove(string studentID) {   
        for (int i = 0; i < 5; i  ) {
            if  (classRosterArray[i]->getId() == studentID) {
                    cout << "removed: " << studentID << endl;
                    delete classRosterArray[i];
                    printAll();
                    return;
                }
            else {
                cout << "The student with the ID: " << studentID << " was not found\n";
            }
        }
    }

edited to add in printAll() function

void Roster::printAll() {
        //prints a complete tab-separated list of student data, each data point indented (tab)
        for (int i = 0; i < 5; i  ) {
            classRosterArray[i]->print();
        }
    }

But printAll() still prints all values regardless. What am I doing wrong?

CodePudding user response:

delete classRosterArray[i];

After this line, classRosterArray[i] will be an invalid pointer (or null if it was before deletion). After this, you call printAll() which contains:

classRosterArray[i]->print();

Here, you attempt to access an object through an invalid pointer. The behaviour of the program is undefined.

What am I doing wrong?

You are indirecting through an invalid pointer. That's wrong. Don't do that. To fix the program, remove the call to printAll(); from remove.

Another thing you're doing wrong: You unnecessarily use bare owning pointers. Don't do that. Probably, classRosterArray should actually be std::vector<Student>. Or, since you're doing search based on a key, perhaps std::unordered_set<std::string, Student> would be appropriate.

CodePudding user response:

delete classRosterArray[i]; is not how you remove something from an array

you do not show how that array is implemented. I hope it is a std::vector, if so you need to use erase

I also hope that the contents of the arrray are std::unique_ptr

but way better would be to put the objects in a std::map with studentID being the key

  • Related