Fix random_sample_n and random_shuffle when RAND_MAX is small

Giovanni Bajo rasky@develer.com
Wed Dec 12 21:31:00 GMT 2018


Hello,

we hit a bug today while cross-compiling a C++ program with mingw32:
if random_shuffle or random_sample_n are called with a sequence of
elements whose length is higher than RAND_MAX, the functions don't
behave as expected because they ignore elements beyond RAND_MAX. This
does not happen often on Linux where glibc defines RAND_MAX to 2**31,
but mingw32 (all released versions) relies on the very old msvcrt.lib,
where RAND_MAX is just 2**15.

I found mentions of this problem in 2011
(http://mingw-users.1079350.n2.nabble.com/RAND-MAX-still-16bit-td6299546.html)
and 2006 (https://mingw-users.narkive.com/gAIO4G5V/rand-max-problem-why-is-it-only-16-bit).

I'm attaching a proof-of-concept patch that fixes the problem by
introducing an embedded xorshift generator, seeded with std::rand (so
that the functions still depend on srand — it looks like this is not
strictly required by the standard, but it sounds like a good thing to
do for backward compatibility with existing programs). I was wondering
if this approach is OK or something else is preferred.

-- 
Giovanni Bajo   ::  rasky@develer.com
Develer S.r.l.  ::  http://www.develer.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: rand.diff
Type: application/octet-stream
Size: 2433 bytes
Desc: not available
URL: <http://gcc.gnu.org/pipermail/gcc-patches/attachments/20181212/d1a9d793/attachment.obj>


More information about the Gcc-patches mailing list