Skip to main content

IAR Embedded Workbench for Arm 9.70.x

CERT-MSC32-C

In this section:
Synopsis

Properly seed pseudorandom number generators

Enabled by default

Yes

Severity/Certainty

Medium/High

mediumhigh.png
Full description

Calling a PRNG in the same initial state, either without seeding it explicitly or by seeding it with the same value, results in generating the same sequence of random numbers in different runs of the program.A long description goes here.

Coding standards
CERT MSC32-C

Ensure your random number generator is properly seeded

Code examples

The following code example fails the check and will give a warning:

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

void func(void) {
  for (unsigned int i = 0; i < 10; ++i) {
    /* Always generates the same sequence */
    printf("%ld, ", random());
  }
}

The following code example passes the check and will not give a warning about this issue:

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

void func(void) {
  struct timespec ts;
  if (timespec_get(&ts, TIME_UTC) == 0) {
    /* Handle error */
  } else {
    srandom(ts.tv_nsec ^ ts.tv_sec);
    for (unsigned int i = 0; i < 10; ++i) {
      /* Generates different sequences at different runs */
      printf("%ld, ", random());
    }
  }
}