Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The C Standard function rand() (available in stdlib.h) does not have good random number properties. The numbers generated by rand() have a comparatively short cycle, and the numbers can be predictable.

...

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>
#include <stdlib.h>
 
void func(void) {
  enum { len = 12 };
  char id[len];  /* id will hold the ID, starting with
                  * the characters "ID" followed by a
                  * random integer */
  int r;
  int num;
  /* ... */
  r = rand();  /* Generate a random integer */
  num = snprintf(id, len, "ID%-d", r);  /* Generate the ID */
  /* ... */
}

Compliant Solution (POSIX)

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void func(void) {
  enum { len = 12 };
  char id[len];  /* id will hold the ID, starting with
                  * the characters "ID" followed by a
                  * random integer */
  int r;
  int num;
  /* ... */
  time_t now = time(NULL);
  if (now == (time_t) -1) {
    /* handle error */
  }
  srandom(now);  /* Seed the PRNG with the current time */
  /* ... */
  r = random();  /* Generate a random integer */
  num = snprintf(id, len, "ID%-d", r);  /* Generate the ID */
  /* ... */
}

The rand48 family of functions provides another alternative for pseudorandom numbers.

...

Code Block
bgColor#ccccff
langc
#include <Windows.h>
#include <wincrypt.h>
#include <stdio.h>
 
void func(void) {
  HCRYPTPROV prov;
  if (CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) {
    long int li = 0;
    if (CryptGenRandom(prov, sizeof(li), (BYTE *)&li))
      printf("Random number: %ld\n", li);
    CryptReleaseContext(prov, 0);
  }
}

Risk Assessment

Using the rand() function leads to possibly predictable random numbers.

...