GCC Newspaper
JUNE 15, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
libstdc++ Performance Win

libstdc++: Prevent overflow in piecewise distribution with empty input.

Avoids reserving size_t(-1) elements when constructing piecewise_constant_distribution or piecewise_linear_distribution with an empty initializer list.

The piecewise_constant_distribution and piecewise_linear_distribution constructors in libstdc++ would attempt to reserve size_t(-1) elements when given an empty initializer list, leading to a crash. This commit fixes this by exiting early for empty or near-empty inputs, and avoids unnecessary memory allocations for default configurations.

In Details

The piecewise_constant_distribution and piecewise_linear_distribution classes in libstdc++ involve internal vectors _M_int and _M_den to store interval boundaries and densities. The constructors were modified to exit early, avoiding allocations when the number of intervals is less than 2. __detail::__load_first2 is used to efficiently check input iterator ranges.

For Context

In C++, distributions generate random numbers according to a probability function. piecewise_constant_distribution and piecewise_linear_distribution create distributions from a set of intervals and corresponding weights or density values. The library needs to allocate storage for these intervals and densities. This commit addresses a bug where passing an empty set of intervals would cause an integer overflow, leading to an attempt to allocate an impossibly large amount of memory.

Filed Under: libstdc++bugfixmemory allocationrandom number generation