Search code examples
c++vectorstliteratorinteger-overflow

What is the outcome of std::distance(v.begin(), v.end()) when v is bigger than INT_MAX?


Consider this code:

std::vector<char>::size_type size = static_cast<std::vector<char>::size_type>(std::numeric_limits<std::vector<char>::difference_type>::max()) + 1;
std::vector<char> v(size);
std::vector<char>::difference_type diff = std::distance(v.begin(), v.end());

where size_type is the same as size_t (unsigned int), and difference_type is the same as ptrdiff_t (signed int).

If the size of the vector is bigger than the limit of difference_type, will the std::distance function return a negative value?


Solution

  • For a random access iterator type, distance(a,b) is defined to be b-a. Subtraction of random access iterators has a precondition:

    pre: there exists a value n of type difference_type such that a + n == b.

    So, if the vector size is too large for difference_type, then you break that precondition, giving undefined behaviour (perhaps a negative result; perhaps something else).