This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: [PATCH] Tighten length error check in string::replace
Benjamin Kosnik wrote:
>>2002-04-24 Paolo Carlini <pcarlini@unitus.it>
>>
>> * include/bits/basic_string.h (replace(__pos, __n1, __s, __n2):
>> Tighten __throw_length_error check.
>>
>>
>testcase?
>
Yes...
Indeed, it turned out to be much more interesting than the fix itself,
in that a length_error may be thrown in many different places for many
different reasons.
I'm not much into exception handling :-(, therefore if you can think of
something appreciably simpler don't hesitate to point it out!
Ciao,
Paolo.
/////////////
2002-04-25 Paolo Carlini <pcarlini@unitus.it>
* include/bits/basic_string.h (replace(__pos, __n1, __s, __n2):
Tighten __throw_length_error check.
* testsuite/21_strings/replace: Add test05.
diff -urN libstdc++-v3-orig/include/bits/basic_string.h
libstdc++-v3/include/bits/basic_string.h
--- libstdc++-v3-orig/include/bits/basic_string.h 2002-04-16
04:29:20.000000000 +0200
+++ libstdc++-v3/include/bits/basic_string.h 2002-04-23
23:55:33.000000000 +0200
@@ -642,10 +642,10 @@
const size_type __size = this->size();
if (__pos > __size)
__throw_out_of_range("basic_string::replace");
- if (__size - __n1 > this->max_size() - __n2)
- __throw_length_error("basic_string::replace");
const bool __testn1 = __n1 < __size - __pos;
const size_type __foldn1 = __testn1 ? __n1 : __size - __pos;
+ if (__size - __foldn1 > this->max_size() - __n2)
+ __throw_length_error("basic_string::replace");
if (_M_rep()->_M_is_shared() || less<const _CharT*>()(__s, _M_data())
|| less<const _CharT*>()(_M_data() + __size, __s))
return _M_replace_safe(_M_ibegin() + __pos,
diff -urN libstdc++-v3-orig/testsuite/21_strings/replace.cc
libstdc++-v3/testsuite/21_strings/replace.cc
--- libstdc++-v3-orig/testsuite/21_strings/replace.cc 2002-04-02
14:07:07.000000000 +0200
+++ libstdc++-v3/testsuite/21_strings/replace.cc 2002-04-25
21:06:33.000000000 +0200
@@ -175,11 +175,29 @@
VERIFY(str02 == "geogaddi");
}
+void
+test05()
+{
+ std::string str01 = "beyond skin";
+ std::string str02 = "glam";
+
+ try {
+ str01.replace(8, 7, str02.c_str(), str02.max_size() - 4);
+ }
+ catch(std::length_error& fail) {
+ VERIFY( std::string(fail.what()) == "basic_string::replace" );
+ }
+ catch(...) {
+ VERIFY( false );
+ }
+}
+
int main()
{
test01();
test02();
test03();
test04();
+ test05();
return 0;
}