Cistoran
Cistoran

Reputation: 1597

Accessing Iterator After Deletion Causes Crash

so I'm used to coding in C# and have just started using C++ again after a pretty substantial break. Essentially what I'm trying to do is to create a program that has lists of students with IDs, in courses.

I have this code that essentially prints out all available students in courses.

auto allCourses = WSUCourse::getAllCourses();
   std::for_each(
       allCourses.begin(),
       allCourses.end(),
       GetCoursePrinter());

The GetCoursePrinter() is called in this code in the constructor

struct GetCoursePrinter
{
   void operator () (
      MyCourse *coursePtr
   )
   {
      std::cout << coursePtr->getIdentifier() <<
         ": " <<
         coursePtr->getTitle() <<
         std::endl;
   }
};

My problem is after I delete an enrollment like so

MyEnrollment *enrollmentPtr = MyEnrollment::findEnrollment(
   MyStudent::getStudentWithUniqueID(1000002),
   MyCourse::getCourseWithIdentifier("CS 2800")
);
delete enrollmentPtr;

And then try to print it with GetCoursePrinter it crashes. I believe this is because it's trying to access something that doesn't exist. What I'm wondering is if there is a way to call something like this

if (allCourses.current() != null)
{
    GetCoursePrinter();
}
else
{
    //do nothing
}

Upvotes: 1

Views: 52

Answers (1)

finesse
finesse

Reputation: 117

when you call:

delete enrollmentPtr;

you need to remove this item in environment.

Upvotes: 1

Related Questions