https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65131
Bug ID: 65131 Summary: Integer overflow in .size() for std::vector Product: gcc Version: 4.9.2 Status: UNCONFIRMED Severity: major Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: fayard at insideloop dot io Hi, The .size() method on the std::vector<T> might overflow. In the case where: - The system has a pointer size of 32 bits - sizeof(T) == 1 - The vector has been created with a size n >= 2^31 Then, as this->_M_impl._M_finish - this->_M_impl._M_start does not fit un a std::ptrdiff_t, this difference has undefined behaviour. // [23.2.4.2] capacity /** Returns the number of elements in the %vector. */ size_type size() const _GLIBCXX_NOEXCEPT { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); } It turns out that max_size() does not prevent us from creating such an array. /** Returns the size() of the largest possible %vector. */ size_type max_size() const _GLIBCXX_NOEXCEPT { return _Alloc_traits::max_size(_M_get_Tp_allocator()); } As I am quite new to C++ so I prefer not to supply a patch. This bug is not present in libc++ and they solved it this way. template <class _Tp, class _Allocator> typename vector<_Tp, _Allocator>::size_type vector<_Tp, _Allocator>::max_size() const _NOEXCEPT { return _VSTD::min<size_type>(__alloc_traits::max_size(this->__alloc()), numeric_limits<size_type>::max() / 2); // end() >= begin(), always } Best regards, Francois