0

Possible Duplicate:
What is the most random function in C++?

In C++, is this safe:

int main() {
srand(time(0));
unsigned char arr[10];
for(int i=0; i <sizeof(arr); ++i)
    arr[i] = (unsigned char)rand();
}

Is there a better way to randomly fill a byte array in a platform independent way? failing that, is there a better way to do this on windows? (I know rand() isn't a very good PRNG, I'm just using it as an example).

Thank you!

Community
  • 1
  • 1
  • 2
    1) How do you define "safe"? 2) If not rand(), then what? – vocaro Jul 18 '11 at 06:53
  • vocaro: 1) No UB. 2) That was my question ;). – Sjint Skovast Jul 18 '11 at 06:54
  • you can also take a look at the generators from C++0x http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15319/ – Marius Bancila Jul 18 '11 at 07:13
  • [According to Julienne Walker](http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx) (chapter “Seeing rand()”), this is UB. – Konrad Rudolph Jul 18 '11 at 07:14
  • @Konrad Rudolph: I think he's got the conversion backwards. It's UB to convert random values _to_ `time_t`. But `time_t` is an arithmetic type, and converting them to an unsigned integral type is safe. You have roughly three potential issues: overflow, underflow, and loss of precision. Overflow is not UB because assigning a value to an unsigned integral types is done modulo 2^N. Underflow and loss of precision (rounding) are well-defined and just result in a lack of randomness. – MSalters Jul 18 '11 at 08:31
  • @MSalters I’m pretty sure *Julienne* is a gal, even though she’s The Dude. To her defense, she doesn’t say it’s UB, merely that it theoretically doesn’t work without problems (though in practice it does). Perhaps I misconstrued that. – Konrad Rudolph Jul 18 '11 at 10:29

1 Answers1

3

What about using boost.random? The generators it uses can be passed to std::generate to fill your array, it's platform independent and headers-only. I would give a code sample but have no boost install available at the moment.

Edit: as mentioned: in C++0x (the upcoming standard), you can use tr1::random, which is essentially just the boost library becoming part of the standard C++ library.

KillianDS
  • 16,936
  • 4
  • 61
  • 70