[libcxx-commits] [libcxx] [libc++] Fix wraparound issue with -fsanitize=integer in string operator>> (PR #106263)

via libcxx-commits libcxx-commits at lists.llvm.org
Tue Aug 27 18:05:03 PDT 2024


================
@@ -1211,12 +1211,11 @@ operator>>(basic_istream<_CharT, _Traits>& __is, basic_string<_CharT, _Traits, _
     try {
 #endif
       __str.clear();
-      streamsize __n = __is.width();
-      if (__n <= 0)
-        __n = __str.max_size();
-      if (__n <= 0)
-        __n = numeric_limits<streamsize>::max();
-      streamsize __c            = 0;
+      using _Size               = typename basic_string<_CharT, _Traits, _Allocator>::size_type;
+      streamsize const __width  = __is.width();
+      _Size const __max_size    = __str.max_size();
+      _Size const __n           = __width <= 0 ? __max_size : std::min(__max_size, static_cast<_Size>(__width));
----------------
zhihaoy wrote:

`static_cast<_Size>(__width)` still wrap around, right? I'm thinking
```cpp
    _Size const __n = [](streamsize __width, _Size __max_size) {
        if (__width <= 0)
            return __max_size;
        else
        {
            auto const __asked = static_cast<std::make_unsigned<streamsize>::type>(__width);
            if (__asked < __max_size)
                return static_cast<_Size>(__asked);
            else
                return __max_size;
        }
    }(__is.width(), __str.max_size());
```

https://github.com/llvm/llvm-project/pull/106263


More information about the libcxx-commits mailing list