[PATCH] libstdc++: do not zero stack buffer in std::bitset extraction
Tomasz Kaminski
tkaminsk@redhat.com
Mon Oct 5 12:11:21 GMT 2026
Looks good, thanks.
On Mon, Oct 5, 2026 at 1:37 PM Jonathan Wakely <jwakely@redhat.com> wrote:
> The stack buffer used for the istream extraction operator does not need
> to be zero-filled before we write to it. To prevent that zeroing from
> happening automatically in C++26 we can use the [[indeterminate]]
> attribute. For C++98 compatibility, __attribute__((uninitialized)) needs
> to be used instead.
>
> Also define a new variable for the array length which is never zero.
> This avoids a -Walloc-size warning in C++98 where the new-expression is
> not a discarded statement so the compiler sees `new _CharT[0]`:
>
> include/bitset:1717: warning: allocation of insufficient size '0' for type
> 'char' with size '1' [-Walloc-size]
>
> libstdc++-v3/ChangeLog:
>
> * include/std/bitset (operator>>): Define __array_len to ensure
> that the array size is never zero. Add uninitialized attribute
> to __buf.
> ---
>
> Tested x86_64-linux.
>
> libstdc++-v3/include/std/bitset | 8 +++++---
> 1 file changed, 5 insertions(+), 3 deletions(-)
>
> diff --git a/libstdc++-v3/include/std/bitset
> b/libstdc++-v3/include/std/bitset
> index 469c8da9ece4..339f0c46cb5c 100644
> --- a/libstdc++-v3/include/std/bitset
> +++ b/libstdc++-v3/include/std/bitset
> @@ -1706,6 +1706,7 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
> typedef typename __istream_type::ios_base __ios_base;
>
> static const bool __use_local = _Nb * sizeof(_CharT) <= 256;
+ static const size_t __array_len = _Nb != 0 ? _Nb : 1;
>
> struct _Buffer
> {
> @@ -1714,7 +1715,7 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
> _Buffer() : _M_ptr(_M_local)
> {
> if _GLIBCXX_CONSTEXPR (!__use_local)
- _M_ptr = new _CharT[_Nb];
> + _M_ptr = new _CharT[__array_len];
> }
>
> ~_Buffer()
> @@ -1725,8 +1726,9 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
> #pragma GCC diagnostic pop
>
> _CharT* _M_ptr;
> - _CharT _M_local[__use_local && _Nb != 0 ? _Nb : 1];
> - } __buf;
> + _CharT _M_local[__use_local ? __array_len : 1];
> + };
> + _Buffer __buf __attribute__((__uninitialized__));
>
> _CharT* __ptr = __buf._M_ptr;
>
> --
> 2.55.0
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://gcc.gnu.org/pipermail/gcc-patches/attachments/20261005/3664a452/attachment.htm>
More information about the Gcc-patches
mailing list