References to invalid memory cells with C ++ Iterators

I am a big fan of GCC, but recently I noticed a foggy anomaly. Using __gnu_cxx :: __ normal_iterator (i.e., the most common type of iterator used in libstdC ++, C ++ STL), you can access an arbitrary memory cell and even change its value without causing an exception! Is this expected behavior? If so, is this not a security loophole?

Here is an example:

#include <iostream>
using namespace std;

int main() {
        basic_string<char> str("Hello world!");
        basic_string<char>::iterator iter = str.end();



        iter += str.capacity() + 99999;
        *iter = 'x';

        cout << "Value: " << *iter << endl;
}
+3
source share
4 answers

Declaring an iterator outside the container from which it was obtained is undefined behavior, and doing nothing is just an opportunity.

, , , , . MSVS ( , , =. .

, Dinkumware (STL VS) ( , ), , , . .

+6

, . , :

for ( type::const_iterator it = obj.begin(); it != obj.end(); ++it ){
    // Refer to element using (*it)
}

end(). , , , < > end(). C ++ , Java, , , .

+2

++ , . , . :

if (iter < str.begin() || iter >= str.end())
    throw something;
+1

. . , .

$ ./a.exe
  11754 [main] a 4992 _cygtls::handle_exceptions: Error while dumping state (probably corrupted stack)
Segmentation fault (core dumped)

Undefined behavior can mean different things on different compilers, platforms, days. Perhaps when you started it, the address created by all this addition accidentally fell into another valid memory space. Maybe you, for example, added from the stack to the heap.

0
source

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


All Articles