简体   繁体   中英

What happens when std::iterator is accessed outside its boundary(end)?

I tried to run below code to check the accessibility of iterator :

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> n = {1,24,5,4};
    vector<int> :: iterator itr;

    itr = n.begin();
    for(;;itr++){
        cout<<*itr<<endl;
    }
    return 0;
} 

The program executed and exited with segmentation fault at the end. What i understood from it that upto certain iterations the value returned by iterator is zero outside its boundary and after that program crashes. I want to know what happens when we access the iterator outside its boundary and if it acts like a pointer , what does it point to?

Anything can happen. It is Undefined Behaviour and the compiler is not required to do anything specific. In fact, it is allowed to treat your entire program as invalid and emit whatever code it wants if your program contains UB anywhere .

Once you break the rules of the language (like dereferencing an iterator pointing to something that is out-of-bounds), you leave the realm of well defined C++ and you can no longer have any expectations as to what the behaviour will be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM