]> gcc.gnu.org Git - gcc.git/commitdiff
libstdc++: Fix infinite loop in std::binomial_distribution [PR114359]
authorJonathan Wakely <jwakely@redhat.com>
Mon, 18 Mar 2024 13:22:17 +0000 (13:22 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Tue, 19 Mar 2024 15:59:44 +0000 (15:59 +0000)
The multiplication (4 * _M_t * __1p) can wraparound to zero if _M_t is
unsigned and 4 * _M_t wraps to zero. The third operand has type double,
so do the second multiplication first, so that we aren't multiplying
integers.

libstdc++-v3/ChangeLog:

PR libstdc++/114359
* include/bits/random.tcc (binomial_distribution::param_type):
Ensure arithmetic is done as type double.
* testsuite/26_numerics/random/binomial_distribution/114359.cc: New test.

libstdc++-v3/include/bits/random.tcc
libstdc++-v3/testsuite/26_numerics/random/binomial_distribution/114359.cc [new file with mode: 0644]

index ade416390b378c5c07865ccce8edbf1757ea5f78..8216883c448e2fd0fe3d1b412f2f5289a6b3c76a 100644 (file)
@@ -1503,7 +1503,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
          // sqrt(pi / 2)
          const double __spi_2 = 1.2533141373155002512078826424055226L;
          _M_s1 = std::sqrt(__np * __1p) * (1 + _M_d1 / (4 * __np));
-         _M_s2 = std::sqrt(__np * __1p) * (1 + _M_d2 / (4 * _M_t * __1p));
+         _M_s2 = std::sqrt(__np * __1p) * (1 + _M_d2 / (4 * (_M_t * __1p)));
          _M_c = 2 * _M_d1 / __np;
          _M_a1 = std::exp(_M_c) * _M_s1 * __spi_2;
          const double __a12 = _M_a1 + _M_s2 * __spi_2;
diff --git a/libstdc++-v3/testsuite/26_numerics/random/binomial_distribution/114359.cc b/libstdc++-v3/testsuite/26_numerics/random/binomial_distribution/114359.cc
new file mode 100644 (file)
index 0000000..c1e4c38
--- /dev/null
@@ -0,0 +1,12 @@
+// { dg-do run { target c++11 } }
+
+// Bug 114359 - std::binomial_distribution hangs in infinite loop
+
+#include <random>
+
+int main()
+{
+  std::default_random_engine g{};
+  std::binomial_distribution<std::uint32_t> b(1U << 30);
+  b(g);  // hangs forever
+}
This page took 0.064799 seconds and 5 git commands to generate.