Default constructed std::random_device doesn't return random number

Viewed 266

I tried to run a simple example from cppreference about std::random_device, but on the line with function call d(rd1) program enters an infinite loop and never returns.

Here is the code:

#include <iostream>
#include <random>
 
int main()
{
 
    std::uniform_int_distribution<int> d(0, 10);
 
    std::random_device rd1;
    for(int n = 0; n < 10; ++n)
        std::cout << d(rd1) << ' ';
    std::cout << '\n';
}

After some inspections I found out that the function std::random_device::operator() always returns value 4294967295 which causes std::uniform_int_distribution<IntType>::operator() to enter an infinite loop.

If I explicitly call constructor with "rdrand" or "/dev/urandom" program works well, but with "rdseed" it's the same wrong result. Also if I link against llvm's libc++ the example works normally. It is worth noting that on Ubuntu 16 and 18 it worked well but on Ubuntu 20 as well as Linux Mint 20 I experienced the issue.

Why is the default constructed random device not working?

uname -a output:

Linux my-pc 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

and some more info about the system: lscpu, lshw

1 Answers

Why is the default constructed random device not working?

Probably something to do with the quality of implementation, or a problem with the execution environment, or a combination of both. This behaviour is certainly not guaranteed by the standard.

In general, one probably shouldn't rely on randomness of std::random_device. At least, combine it with another seed and / or a pseudo random number.

Related