2

Let's say I have the following code:

std::vector< int > from( 5 );
std::vector< int > to( 10 );
std::copy( from.begin(), from.begin() + 10, to.begin() );

or it maybe

std::vector< int >::iterator e = from.begin();
std::advance( e, 10 );
std::copy( from.begin(), e, to.begin() );

when I ran it with Visual Studio in Debug mode I got an assert failed with text "iterator is out of range". When I ran it with GCC - LWS link - I got nothing, but incorrect working.

Now the question: is there GCC option to switch on run-time comparing iterators for correct range and either to throw appropriate exception or to call assert if iterator is out of range.

P.S. I clearly know, that code is incorrect and maybe has UB. And I know how to correct it, but I want GCC to help me in future ))

Randy Howard
  • 2,165
  • 16
  • 26
borisbn
  • 4,988
  • 25
  • 42
  • MSVC++, only in debug mode, checks validity of the iterator. If it is invalid, it asserts with "out of range" message. – Nawaz Mar 28 '13 at 12:45
  • Well the thing about undefined behavior is that it's undefined, it might work sometimes, some implementations define their own behavior, or it can even cause [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude Mar 28 '13 at 12:47
  • @Nawaz Yes, of course. I forgot to say about `Debug` mode. I'll edit – borisbn Mar 28 '13 at 12:47
  • [Try](http://stackoverflow.com/questions/2567997/using-a-checked-stl-implementation-anything-available-for-free) [these](http://stackoverflow.com/questions/5594686/gcc-stl-bound-checking) [links](http://gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode.html). – BoBTFish Mar 28 '13 at 12:51
  • @BoBTFish The first link was enough. adding `-D_GLIBCXX_DEBUG` to command-line (as was answered at link you gave) solved problem - [LWS](http://liveworkspace.org/code/jgipc$8). Could you make your comment as answer to accepting it, please ? – borisbn Mar 28 '13 at 12:56
  • I don't think I should just copy someone else's answer. It would be more appropriate to close this as a duplicate I think. – BoBTFish Mar 28 '13 at 13:09
  • @borisbn: You can either wait for the question to be closed as duplicate or do it yourself... add a first line with the link and a comment then close it. Also note that checked iterators come at a price: there is a performance cost, and in general (haven't looked at the gcc implementation) they are not binary compatible with the non-checked version of the library. That is, you should not mix binaries compiled with/without the flag. – David Rodríguez - dribeas Mar 28 '13 at 13:22
  • 1
    @BoBTFish and DavidRodríguez-dribeas Ok, I understood you and will close (as you suggest). Nevertheless - thank you )) – borisbn Mar 28 '13 at 13:35

0 Answers0