Reputation: 21
#include<list>
#include<iostream>
using namespace std;
list<int> DL,TRS;
list<int>::iterator gitr;
void exchange();
int main() {
DL.push_back(10);
gitr=DL.begin();
TRS.push_back(11);
TRS.push_back(12);
exchange();
cout<<(*gitr)<<endl;
}
void exchange() {
list<int> tdl;
tdl=DL;
DL.clear();
DL=TRS;
list<int>::iterator tmpitr=DL.begin();
for(;tmpitr!=DL.end();++tmpitr)
cout<<(*tmpitr)<<endl;
DL.clear();
DL=tdl;
}
This outputs 11 instead of 10. Why?
Upvotes: 1
Views: 669
Reputation: 76848
This program invokes undefined behavior, and is therefore allowed to do anything it wants - even printing 11 instead of 10.
Why is it UB? Because gitr
is assigned DL.begin()
, and then (inside the function exchange
) DL
is cleared, making gitr
an invalid iterator. Dereferencing that iterator is UB.
Upvotes: 2