public inbox for libstdc++@gcc.gnu.org
 help / color / mirror / Atom feed
* [committed] libstdc++: More fixes for null pointers used with std::char_traits
@ 2023-03-28 20:15 Jonathan Wakely
  0 siblings, 0 replies; only message in thread
From: Jonathan Wakely @ 2023-03-28 20:15 UTC (permalink / raw)
  To: libstdc++, gcc-patches

Tested powerpc64le-linux. Pushed to trunk.

-- >8 --

The std::char_traits member functions require that [p,p+n) is a valid
range, which is true for p==nullptr iff n==0. But we must not call
memcpy, memset etc, in that case, as they require non-null pointers even
when n==0.

This std::char_traits<char> and std::char_traits<wchar_t> explicit
specializations are already correct, but the primary template has some
bugs.

libstdc++-v3/ChangeLog:

	* include/bits/char_traits.h (char_traits::copy): Return without
	using memcpy if n==0.
	(char_traits::assign): Likewise for memset.
---
 libstdc++-v3/include/bits/char_traits.h | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/libstdc++-v3/include/bits/char_traits.h b/libstdc++-v3/include/bits/char_traits.h
index cfc7d0f0e14..68ed827f982 100644
--- a/libstdc++-v3/include/bits/char_traits.h
+++ b/libstdc++-v3/include/bits/char_traits.h
@@ -263,6 +263,8 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
     char_traits<_CharT>::
     copy(char_type* __s1, const char_type* __s2, std::size_t __n)
     {
+      if (__n == 0)
+	return __s1;
 #if __cplusplus >= 202002L
       if (std::__is_constant_evaluated())
 	{
@@ -271,7 +273,6 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 	  return __s1;
 	}
 #endif
-
       __builtin_memcpy(__s1, __s2, __n * sizeof(char_type));
       return __s1;
     }
@@ -293,9 +294,12 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
 
       if _GLIBCXX17_CONSTEXPR (sizeof(_CharT) == 1 && __is_trivial(_CharT))
 	{
-	  unsigned char __c;
-	  __builtin_memcpy(&__c, __builtin_addressof(__a), 1);
-	  __builtin_memset(__s, __c, __n);
+	  if (__n)
+	    {
+	      unsigned char __c;
+	      __builtin_memcpy(&__c, __builtin_addressof(__a), 1);
+	      __builtin_memset(__s, __c, __n);
+	    }
 	}
       else
 	{
-- 
2.39.2


^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2023-03-28 20:15 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-03-28 20:15 [committed] libstdc++: More fixes for null pointers used with std::char_traits Jonathan Wakely

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).