https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124370
Bug ID: 124370
Summary: Out-of-bounds write for wistream >> bitset
Product: gcc
Version: 13.1.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: libstdc++
Assignee: unassigned at gcc dot gnu.org
Reporter: dolsen at nvidia dot com
Target Milestone: ---
Function
template<class _CharT, class _Traits, size_t _Nb>
std::basic_istream<_CharT, _Traits>&
operator>>(std::basic_istream<_CharT, _Traits>& __is, bitset<_Nb>& __x)
in header <bitset> has an out-of-bounds write bug for wide character streams
and small bitsets (N < 256).
In this code:
```
if _GLIBCXX_CONSTEXPR (_Buffer::_S_use_alloca())
__ptr = (_CharT*)__builtin_alloca(_Nb);
else
__ptr = new _CharT[_Nb];
```
`__builtin_alloca(_Nb)` is fine when `_CharT` is `char`, but it doesn't
allocate enough memory when `_CharT` is `wchar_t`. It should be
`__builtin_alloca(_Nb * sizeof(_CharT))` instead.
This test program demonstrates the problem. When compiled with GCC 15 on Linux
x86_64, I get a runtime seg fault due to the stack being overwritten.
```
#include <bitset>
#include <sstream>
#include <iostream>
void init_set(std::bitset<10>& bset) {
std::wistringstream input(L"10011011001101");
input >> bset;
}
int main() {
std::bitset<10> bset;
init_set(bset);
for (int i = 0; i < 10; ++i) {
std::cout << (int)bset.test(i) << " ";
}
std::cout << "\n";
}
```
This bug was introduced in 13.1 and it appears to still be present.