From 0876da45db4b39650bcf8d1f449b9e1ec8c0c430 Mon Sep 17 00:00:00 2001 From: Marshall Clow Date: Mon, 13 Feb 2017 10:49:17 -0800 Subject: [PATCH] Fix potential overflow in substr; Trac #11536. Also change string_view::copy to use the traits::copy --- include/boost/utility/string_ref.hpp | 4 +--- include/boost/utility/string_view.hpp | 8 ++------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/include/boost/utility/string_ref.hpp b/include/boost/utility/string_ref.hpp index 96ab439..ea4ade0 100644 --- a/include/boost/utility/string_ref.hpp +++ b/include/boost/utility/string_ref.hpp @@ -162,9 +162,7 @@ namespace boost { basic_string_ref substr(size_type pos, size_type n=npos) const { if ( pos > size()) BOOST_THROW_EXCEPTION( std::out_of_range ( "string_ref::substr" ) ); - if ( n == npos || pos + n > size()) - n = size () - pos; - return basic_string_ref ( data() + pos, n ); + return basic_string_ref(data() + pos, (std::min)(size() - pos, n)); } int compare(basic_string_ref x) const { diff --git a/include/boost/utility/string_view.hpp b/include/boost/utility/string_view.hpp index c48a515..a92d0f7 100644 --- a/include/boost/utility/string_view.hpp +++ b/include/boost/utility/string_view.hpp @@ -183,18 +183,14 @@ namespace boost { if (pos > size()) BOOST_THROW_EXCEPTION(std::out_of_range("string_view::copy" )); size_type rlen = (std::min)(n, len_ - pos); - // use std::copy(begin() + pos, begin() + pos + rlen, s) rather than - // std::copy_n(begin() + pos, rlen, s) to support pre-C++11 standard libraries - std::copy(begin() + pos, begin() + pos + rlen, s); + traits_type::copy(s, data() + pos, rlen); return rlen; } BOOST_CXX14_CONSTEXPR basic_string_view substr(size_type pos, size_type n=npos) const { if ( pos > size()) BOOST_THROW_EXCEPTION( std::out_of_range ( "string_view::substr" ) ); - if (n == npos || pos + n > size()) - n = size () - pos; - return basic_string_view(data() + pos, n); + return basic_string_view(data() + pos, (std::min)(size() - pos, n)); } BOOST_CXX14_CONSTEXPR int compare(basic_string_view x) const BOOST_NOEXCEPT {