]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Fix undefined behaviour in std::string
authorJonathan Wakely <jwakely@redhat.com>
Tue, 4 May 2021 14:49:38 +0000 (15:49 +0100)
committerJonathan Wakely <jwakely@redhat.com>
Tue, 4 May 2021 21:45:02 +0000 (22:45 +0100)
This fixes a ubsan error when constructing a string with a null pointer:

bits/basic_string.h:534:21: runtime error: applying non-zero offset 18446744073709551615 to null pointer

The _M_construct function only cares whether the second pointer is
non-null, so create a non-null value without undefined arithmetic.

We can also pass the random_access_iterator_tag directly to the
_M_construct function, to avoid going via the tag dispatching
_M_construct_aux, because we know we have pointers not integers here.

libstdc++-v3/ChangeLog:

* include/bits/basic_string.h (basic_string(const CharT*, const A&)):
Do not do arithmetic on null pointer.

libstdc++-v3/include/bits/basic_string.h

index fba7c6f335418790faec2d31488292ebb98ef53b..84356adc7ae5ffe167d0fb52052a5dfcfe9e7e87 100644 (file)
@@ -531,7 +531,12 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11
 #endif
       basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
       : _M_dataplus(_M_local_data(), __a)
-      { _M_construct(__s, __s ? __s + traits_type::length(__s) : __s+npos); }
+      {
+       const _CharT* __end = __s ? __s + traits_type::length(__s)
+         // We just need a non-null pointer here to get an exception:
+         : reinterpret_cast<const _CharT*>(__alignof__(_CharT));
+       _M_construct(__s, __end, random_access_iterator_tag());
+      }
 
       /**
        *  @brief  Construct string as multiple characters.