Reputation: 3698
In this sample program, why the value of the data pointed by the iterator is kept, even after the list is empty?
Is it something bound to happen due to the implementation of iterators in C++ (i.e. the value of the object is kept into the iterator) or is it because the segment of the memory was declared as free for used, but hasn't been changed yet?
#include <iostream>
#include <list>
using namespace std;
int main ()
{
list<int> mylist;
list<int>::iterator it = mylist.begin();
cout << "printing: " << *it << endl;
mylist.push_back(77);
mylist.push_back(22);
// now front equals 77, and back 22
mylist.front() -= mylist.back();
it = mylist.begin();
cout << "printing: " << *it << endl;
cout << "mylist.front() is now " << mylist.front() << '\n';
// trying to delete all elements and then see how the iterators are handling it
it = mylist.begin();
cout << "printing: " << *it << endl;
mylist.remove(55);
cout << "printing: " << *it << endl;
mylist.remove(22);
cout << "printing: " << *it << endl;
cout << "mylist size: " << mylist.size() << endl;
cout << "mylist.front() is now " << mylist.front() << '\n';
cout << "printing: " << *it << endl;
return 0;
}
And this is the output:
printing: 495034304
printing: 55
mylist.front() is now 55
printing: 55
printing: 55
printing: 55
mylist size: 0
mylist.front() is now 38375440
printing: 55
Upvotes: 0
Views: 98
Reputation: 3886
#include <stdio.h>
int main(int argc, char **argv)
{
int *p = NULL;
p = (int*)malloc(sizeof(int));
*p = 5;
printf("P: %d\n", *p);
free(p);
printf("P: %d\n", *p);
}
Why is this still a surprise? Marking a pointer as invalid has nothing to do with what is stored where it used to point.
Upvotes: 1
Reputation: 254631
Is it something bound to happen due to the implementation of iterators in C++
No, it's undefined behaviour. The iterator has become invalid, and can't be used.
is it because the segment of the memory was declared as free for used, but hasn't been changed yet?
Yes, that's why you observed what you observed. But the memory could be reused for something else, or made inaccessible - you can't rely on any observations of undefined behaviour.
Upvotes: 6
Reputation: 21003
Iterator is invalidated by you operations, but it may still point to memory with the previous value. Anyway, accessing it after the value is removed from the list is undefined behaviour.
Upvotes: 3