Bound Iterator Check in Release Mode (C ++)

I intentionally made an iterator to exceed the size of std::vector like,

 for (std::vector <Face>::iterator f = face.begin(); f!=face.end()+5; ++f) { // here I try to access (*f).P // note that I added 5 to the face.end() } 

I did not encounter any error either at compile time or at runtime. How can I prevent this?

+4
source share
3 answers

If you want to check access to vector elements, you can use the at function, which throws an exception std::out_of_range in case of violation of the border. Example:

 for (std::vector<Face>::size_type i = 0; i != face.size()+5; ++i) { face.at(i).f(); } 

The standard does not specify any valid iterators. The wording in the standard is that access to an invalid iterator leads to undefined behavior. But many implementations provide proven iterators. If portability is not a concern, you can use one of these proven iterators. For example, in debug mode, MSVC vector<T>::iterator is a proven iterator. However, in Release mode, it's just a typedef for T*

+4
source

Which C ++ compiler do you use? VC10 (i.e. C ++ Compiler in VS2010) in the debug assembly correctly identifies the problem:

 // Compile with: // cl /EHsc /W4 /nologo /D_DEBUG /MDd test.cpp #include <iostream> #include <string> #include <vector> class Face { public: std::string Name; explicit Face(const std::string & name) : Name(name) {} }; int main() { std::vector<Face> faces; faces.push_back( Face("Connie") ); faces.push_back( Face("John") ); for ( std::vector <Face>::iterator f = faces.begin(); f != faces.end() + 5; ++f) { std::cout << f->Name << std::endl; } return 0; } 

When the resulting .exe is executed, a dialog box appears with an error message:

Expression: vector iterator + offset out of range

+1
source

For the version of the C ++ standard library version, you won’t get a check on the built-in boundaries of your iterators (or other operations that might be cleared), because it will be relatively slow. However, this does not mean that you need to compile in debug mode: as far as I understand the debug mode of libstdC ++, it can be used when compilation with compiler optimization is enabled. I suspect this is true for other proven STL implementations, because the verified code is usually just controlled by setting some macros accordingly. To do this, you need to find the appropriate macro parameters and configure them accordingly using what you use to create the code.

0
source

Source: https://habr.com/ru/post/1391015/


All Articles