This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

random number generators - rand(), random(), etc


Hi,

Why, with seed "none", random() and rand() behave differently w/r to
auto seeding with 1 ?

Why, with seed 1, rand() in glibc behaves differently from what the ISO C
standard says ?

Why, with seeds 0 and 1, random() and rand() generate same random numbers ?

Are any of these a security problem ?

Note:
RANDOM(3)                  Linux Programmer's Manual
  If no seed value is provided,  the  rand()  function  is  automatically
  seeded with a value of 1.

RAND(3)                    Linux Programmer's Manual
  If no seed value is provided,  the  rand()  function  is  automatically
  seeded with a value of 1.

RAND(3)                     Linux Programmer's Manual
  The versions of rand() and srand() in the Linux C Library use the  same
  random number generator as random(3) and srandom(3), (...)

srand()  
ISO C standard
http://www.cplusplus.com/reference/cstdlib/srand/
  If seed is set to 1, the generator is reinitialized to its initial value 
  and produces the same values as before any call to rand or srand.

random.c:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  unsigned int s;
  int j;

  printf("--- srandom(s), random()\n");
  printf("seed\trandom numbers\n");
  printf("none");
  for (j=0; j<=1; ++j)
  {
    printf("\t%li", random());
  }
  printf("\n");
  for (s=0; s<=3; ++s)
  {
    int i;
    for (i=0; i<=1; ++i)
    {
      srandom(s);
      printf("%i", s);
      for (j=0; j<=1; ++j)
      {
        printf("\t%li", random());
      }
      printf("\n");
    }
  }

  printf("\n");

  printf("--- srand(s), rand()\n");
  printf("seed\trandom numbers\n");
  printf("none");
  for (j=0; j<=1; ++j)
  {
    printf("\t%i", rand());
  }
  printf("\n");
  for (s=0; s<=3; ++s)
  {
    int i;
    for (i=0; i<=1; ++i)
    {
      srand(s);
      printf("%i", s);
      for (j=0; j<=1; ++j)
      {
        printf("\t%i", rand());
      }
      printf("\n");
    }
  }

  return 0;
}

$ gcc -Wall -o random random.c 
$ ./random 
--- srandom(s), random()
seed	random numbers
none	1804289383	846930886
0	1804289383	846930886
0	1804289383	846930886
1	1804289383	846930886
1	1804289383	846930886
2	1505335290	1738766719
2	1505335290	1738766719
3	1205554746	483147985
3	1205554746	483147985

--- srand(s), rand()
seed	random numbers
none	844158168	953350440
0	1804289383	846930886
0	1804289383	846930886
1	1804289383	846930886
1	1804289383	846930886
2	1505335290	1738766719
2	1505335290	1738766719
3	1205554746	483147985
3	1205554746	483147985

jb



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]