Coder's Guild Mailing List

Seeding random number generators (was: Re: using rand for cplus)

Posted by Benjamin Johnston on 1999-10-05

> an easy way to do it is to just put
> srand(time(NULL));
> at the top of your function.  Remember to include time.h so you can use
> the time() function.

Both Morgan and Stormbringer are perfectly correct.
But it should be mentioned/reinforced that in general srand should only be
called once in the entire program (or rarely as possible anyway).

This point is extremely important. I remember some code I had to debug once,
it was a function that a friend had written and worked perfectly during
debugging (it generated special types of random numbers). But the instant
that it was used in a program it became instantly predictable.

The problem was that it called srand every time the function was called.
This was fine during debugging, because the duration between function calls
are pretty random (since they are executed on the programmers request). Once
the function was put into a program, the program would call the function
many times repeatedly. So fast that when the function got the time, it would
get the same answer (because of the low timer resolution), so that the
function would seed the random number with the identical number each time it
was called.

The moral of the story is to only put srand calls in init routines, or as
one of the first lines in the main method. This guarantees that the srand
function will only be called once, and that the random numbers will
different and unpredictable (in the most part).

This pseudo-random-number-generator seeding 'bug' crops up fairly often.
Just the other day I read about how some company's e-gambling website seeded
the random number generator it used for card-shuffling, at the start of each
game. When some employees in a different division of that same company had a
go at cracking the system, they discovered that they once they synchronized
their own clocks with that of the system, they could predict the 'shuffled
deck', simply by knowing (or estimating) what time the game started. They
have fixed the bug up now, and they dont think any hackers exploited the
bug... but I cant remember the details too well. If anybody's interested and
I come across the article again, I'll email it in to TCG.

-Benjamin Johnston
s355171@xxxxxxx.xx.xxx.xx

Correction: Technically, it doesn't matter how many times srand is called if
there are no interspersed calls to rand. So, it's ok to have srand called in
every initialization function since only the last call to srand will count.
But as soon as rand is called (after the initialization, and when the
program is in the middle of execution) srand should not be called again,
unless you are COMPLETELY sure that the current time will be random, and
that it is absolutely necessary to call srand again.