From charlesreid1

Exploring some curious random number behavior in C++...

Simple Program

Put this code in a file called myrand.cpp

#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <iostream>

using std::cout;
using std::endl;

int main ()
{
  int mynum;
  srand (time(NULL)); /* initialize random seed */
  for( int i = 0; i < 5; i++) {
    cout << rand() << endl;
  }
  return 0;
}

Compilation

Compile with g++:

$ g++ myrand.cpp

Output

Run it:

$ ./a.out

Here is the output from my terminal when I run this program:

charles @ cronus [ 2016-06-21 - 15:00:12 - 41 ] /temp $ ./a.out
1575746672
805981500
1951708871
1705770619
2127589730

charles @ cronus [ 2016-06-21 - 15:00:13 - 42 ] /temp $ ./a.out
1575763479
1088456749
1426875297
543230630
1124215013

charles @ cronus [ 2016-06-21 - 15:00:14 - 43 ] /temp $ ./a.out
1575780286
1370931998
902041723
1528174288
120840296

charles @ cronus [ 2016-06-21 - 15:00:15 - 44 ] /temp $ ./a.out
1575797093
1653407247
377208149
365634299
1264949226

Curious Behavior

Notice how the first random number that is generated is always starting at around 15757XXXXX. Seeding the random number generator with the current time seems to generate very similar (read: NOT random) numbers for the first random number.

I hope the people who design cryptosystems know about this!

More Curious Behavior

time(NULL) only generates a unique integer once per second.

That means, if you run the program repeatedly with NO delays in-between, time(NULL) will always generate the same random number if it is still the same second, and so you will get the exact same numbers if you run the program over and over in a 1-second interval. For example:

charles @ cronus [ 2016-06-21 - 15:08:22 - 69 ] /temp $ ./a.out && ./a.out && ./a.out && ./a.out && ./a.out
1584133365
27210049
2052760379
1418900798
1807295698

1584133365
27210049
2052760379
1418900798
1807295698

1584133365
27210049
2052760379
1418900798
1807295698

1584133365
27210049
2052760379
1418900798
1807295698

1584133365
27210049
2052760379
1418900798
1807295698