473,796 Members | 2,649 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

No out_of_range exception for "iterator + n" vs. vector.at( n )

Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range exception?
Maybe this is a gcc issue?

I'm using gcc version 3.3.3 (cygwin special).

Here's the full sample code:

#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

int main() {
vector<int> code;
code.push_back( 10L );
code.push_back( 20L );

vector<int>::it erator iter = code.begin();
try {
cout << *(iter + 5) << endl; // 0
cout << code.at( 10 ) << endl; // vector [] access out of range
} catch( out_of_range e ) {
cout << e.what() << endl;
}

return 0;
}
Thanks,
Mike

Jul 22 '05
13 5081
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:34******** *************@b gtnsc04-news.ops.worldn et.att.net...
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:0L******** *************@b gtnsc04-news.ops.worldn et.att.net...
Hi all. Just working on a small virtual machine, and thought about using
vector iterators instead of pointer arithmetic. Question is, why does an
iterator plus any number out of range not generate a out_of_range

exception?
Maybe this is a gcc issue?


Thanks for everyone's reply. The reason I ask is that I want to point to
a
index into vector, then read an offset by that. I could use code.at( ip +
offset ), but I wanted to do everything with iterators. I realize [] does
no bounds checking, but did not know that (iter + n) does not either.

"iter + 0" is the selector
"iter + 1" is the first argument
etc.


So you would need to do a check such as:
if( vect.end()-iter < 2 ) { /* throw invalid position error */ }

Note that, being a random iterator, vector::iterato r supports
the following syntax, just like native pointers:
iter[pos] // equivalent to *(iter+pos), but maybe nicer...

Finally, note that some implementations of the standard library
support a debug mode where the ranges of all iterators (and
other consistency checks) are made automatically.
(STLport is one such implementation, I do not know about gcc's).
This doesn't help write portable code, but can be helpful
during debugging.

Regards,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #11
"Ivan Vecerina" <IN************ *************** **@vecerina.com > wrote in
message news:cl******** **@newshispeed. ch...
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:s9******** *********@newsr ead3.news.pas.e arthlink.net...
If you don't use the protection of 'vector::at()' you can still protect
yourself by [..snip..] comparing against 'vector::end()' , etc.


Note that it is not obvious to compare against end(), because it may
be too late to avoid Undefined Behavior (UB):
iter += 5; // if result is > vect.end(), UB happens here!
if( iter >= vect.end() ) { ... /* but it's too late */ ... };


I was simply listing possible functions to use, depending upon
context. I wasn't trying to imply that 'end()' could protect
against e.g. 'iter+5' where that is out of bounds. 'end()'
would of course apply to iterating via a loop. I did presume
the OP would actually read about these functions before using
them.

-Mike
Jul 22 '05 #12
"Ivan Vecerina" <IN************ *************@v ecerina.com> wrote in message
news:cl******** **@newshispeed. ch...
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:34******** *************@b gtnsc04-news.ops.worldn et.att.net...
"iter + 0" is the selector
"iter + 1" is the first argument
etc.


So you would need to do a check such as:
if( vect.end()-iter < 2 ) { /* throw invalid position error */ }

Note that, being a random iterator, vector::iterato r supports
the following syntax, just like native pointers:
iter[pos] // equivalent to *(iter+pos), but maybe nicer...

Finally, note that some implementations of the standard library
support a debug mode where the ranges of all iterators (and
other consistency checks) are made automatically.
(STLport is one such implementation, I do not know about gcc's).
This doesn't help write portable code, but can be helpful
during debugging.


I would like to use exceptions, rather than put code checks around
everything. It's just cleaner and more structured.
I don't know exactly how to implement 'safe_iterator' , but the following is
a start. Would anyone like to give me a hint?

template <typename T>
class safe_iterator : public T::iterator {
Value operator ++() {
if( *this == container->end() ) // how to access "container" ?
throw out_of_range( "operator vector ++(): out of range" );
else
T::iterator::op erator ++();
}
};

Regards,
Mike

Jul 22 '05 #13
"Mike Austin" <mi**@mike-austin.com> wrote in message
news:s6******** **********@bgtn sc05-news.ops.worldn et.att.net...
"Ivan Vecerina" <IN************ *************@v ecerina.com> wrote in
message
news:cl******** **@newshispeed. ch... .....
Finally, note that some implementations of the standard library
support a debug mode where the ranges of all iterators (and
other consistency checks) are made automatically.
(STLport is one such implementation, I do not know about gcc's).
This doesn't help write portable code, but can be helpful
during debugging.


I would like to use exceptions, rather than put code checks around
everything. It's just cleaner and more structured.
I don't know exactly how to implement 'safe_iterator' , but the following
is
a start. Would anyone like to give me a hint?

template <typename T>
class safe_iterator : public T::iterator {


Derivation is unsafe here (especially once you need
to add a data member). Unfortunately you should prefer
containment (store the base iterator as a data member).
Value operator ++() {
if( *this == container->end() ) // how to access "container" ?
throw out_of_range( "operator vector ++(): out of range" );
else
T::iterator::op erator ++();
}
};


You need to store a pointer to the container within the iterator.
Then you can use it to test for valid bounds, but eventually also
for validating iterator pairs during comparisons.
For example:
template<typena me T>
bool operator ==( safe_iterator<T > const& a
, safe_iterator<T > const& b )
{
if( a.pContainer != b.pContainer ) throw( .... );
return a.base == b.base;
};
[ What you cannot reliably check for this way is whether the
iterator is being used after having been invalidated
by a call modifying the contents of the container ]

It is not a trivial task to implement a complete iterator
interface, although some libraries can help with this
(http://www.boost.org/libs/utility/op....htm#iterator).
But in the end, implementing fully checked iterators
takes some real effort, and implies that many redundant
error checks will be included in the compiled code.
The philosophy of the STL is that operations are performed
on a valid range specified by two iterators. This way you
check upfront that the range is valid/has enough elements,
and then you perform all operations without further overhead.

I do not know specifically what you are implementing, but
if fully implementing a safe iterator seems excessively
complex, maybe you can try to adapt your approach to the
problem?
Alternatively, consider writing a few non-member functions
that encapsulate the essential operations for which you need
range checking.
E.g.:
template<class Cont, class Iter>
Iter checkedOffset(C ont const& c, Iter const& p, int offset)
{
if( offset>0 && (c.end() - p)<=offset ) throw(....);
if( offset<0 && (c.begin()-p)> offset ) throw(....);
return p+offset;
}

Regards,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
4867
by: gregory_may | last post by:
I have an application I created called "JpegViewer.exe". It simply loads a Jpeg file and displays in on the screen. It works great, in my lab. When I am using it at a customer site, things change. Occasionally, it blows up with an Application Exception. It seems to only die at the customer site
2
58136
by: Chris Herring | last post by:
Hi there: Well, let me start off by saying that I am a Visual Studio drag and drop weenie, not a real programmer. So I tend to get confused when things do not look like the instructions said they were going to look :) . Here is my current dilemma: I am having a strange problem with my ASP.NET application. I am building the application using Visual Basic .Net in Visual Studio.NET 2003. Lately, I have frequently been getting the following...
0
1589
by: Lionel B | last post by:
Greetings, Using gcc (GCC) 3.3.3 (cygwin special) on Win2K Does anyone know if there is a convenient mechanism to cause a C++ exception to be thrown whenever a IEEE 754 floating-point "exception" is raised? Currently I a check the FPU status word wherever I wish to test for FP errors and throw a C++ exception accordingly. This is fine; but
5
2705
by: Peter Steele | last post by:
We have an application that when it runs in the IDE in debug mode an unhandled exception is occurring in a system header file associated with STL stirngs. The actual statement that crashes is return ::memcmp(_First1, _First2, _Count); On inspecting these variables, the strings are in fact equal when the exception occurs and _Count is the right size. As a test I replaced this code in the system include file with a for loop to do the...
7
9538
by: Søren Dreijer | last post by:
Hi, I have a mixed C#, managed C++ and unmanaged C++ project. The managed class calls a method which exists in an unmanaged singleton class. During the entire lifetime of the application, this gives no problems whatsoever. However, upon shutdown an exception pops up: "The string binding is invalid" If I call the singleton method from inside a purely unmanaged class, I
4
2902
by: R.A.M. | last post by:
Hello, Could you help me plase? I have an ASP.NET page with "Search" button; when button is clicked Search_Click is called; here's the code: protected void Search_Click(object sender, EventArgs e) { Debug.WriteLine("WWWPage.Search_Click()"); ... try
1
3019
by: R.A.M. | last post by:
Hello, Could you help me plase? I am describing my problem second time because I haven't got a solution. I have an ASP.NET page with "Search" button; when button is clicked Search_Click is called; here's the code: protected void Search_Click(object sender, EventArgs e) { Debug.WriteLine("WWWPage.Search_Click()"); ...
2
24525
by: Abubakar | last post by:
Hi all, I'm writing an app in vc++ 2k5 (all native/unmanaged). This application does a lot of multithreading and socket programming. Its been months since I'm developing this application, at this point a lot of it is working just fine, my app running fine, threads r being made and destroyed, memory is being dynamically allocated at God knows how many places and ,hopefully, getting deallocated as well. Its just by coincedence I happened...
2
2859
by: dkmd_nielsen | last post by:
I have two rather simple class methods coded in Ruby...my own each iterator: The iterator is used internally within the class/namespace, and be available externally. That way I can keep everything hidden about the "instructions table." # Loop through each instruction in the block, yielding the result from # the specified code block. def each(&logic) @instructions.each {|instr| yield instr} end
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9047
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5568
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.