简体   繁体   中英

Dereferencing an out-of-range vector iterator - what happpens and why?

Running this on my setup:

  vector<int> myvector;
  for (int i=1; i<=5; i++) myvector.insert(myvector.end(),i);

  vector<int>::iterator it;
  for ( it=myvector.begin() ; it < myvector.end()+2; it++ )
    cout << " " << *it;

Yields:

1 2 3 4 5 0 0

I would have thought that trying to dereference an out-of-range iterator would have resulted in a segfault. But it seems to yield an empty or default-initialized object of the type contained in the vector.

Is this well defined behaviour? And where does this property come from, from the iterator or from the vector? Does the iterator in some sense catch the out-of-range-exception and instead return an empty object?

I tried finding this in the C++11 reference, but it feels like it's a bit over my head.

This is undefined behavior, which means anything could happen, including segfault, or what you have experienced, or anything else. Basically, you were just lucky it didn't crash (or unlucky, based on the point of view).

I would have thought that trying to dereference an out-of-range iterator would have resulted in a segfault.

No, it gives undefined behaviour. The language does not require iterator accesses to be checked, as that would require a run-time check. C++ usually tries to avoid unnecessary run-time overhead, leaving the programmer to perform whatever checks are necessary.

Most modern platforms use paged virtual memory, providing memory protection with a granularity of a few kilobytes. This means that there is often accessible memory after an allocated block (such as the one managed by std::vector ), in which case out-of-range accesses will simply stomp on that memory.

It may be possible to enable run-time iterator checks in your C++ library; alternatively, tools such as valgrind or efence can help to debug various memory errors, including out-of-range accesses.

C++ Vector implementation is done using arrays- if the size exceeds, then it increases the size of underlying array:
Here is some interesting code that Facebook had open sourced a while back- The comments on memory management are a great way to know more what goes under the hoods Facebook FBvector

The result what you get is equivalent of out-of-bounds accessing of a 'C array' - random :-)

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