Main Content

MISRA C:2023 Rule 21.24

The random number generator functions of <stdlib.h> shall not be used

Since R2024a

Description

Rule Definition

The random number generator functions of <stdlib.h> shall not be used.

Rationale

The numbers generated by rand() are pseudorandom and depend on a seed set by srand(). Because of this, the numbers generated by rand() can be predicted and are cryptographically weak. Using srand() by itself is superfluous as the code sets a seed value for random number generation but does not use it.

Polyspace Implementation

Polyspace® reports a violation of this rule whenever the code contains rand() or srand().

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

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

volatile int rd = 1;
int main(int argc, char *argv[])
{   
	int j, r, nloops;
	struct random_data buf;
	int i = 0;
	
	nloops = rand();                      //Noncompliant
	
	for (j = 0; j < nloops; j++) {
		i = rand();                    //Noncompliant
		printf("random_r: %ld\n", (long)i);
	}
	return 0;
}

In this example, rand() generates random numbers nloops and i. Polyspace reports both uses of rand() as a violation of MISRA C:2012 Rule 21.24. Use more cryptographically sound pseudorandom number generators (PRNGs), such as CryptGenRandom (Windows®), OpenSSL/RAND_bytes (Linux®/UNIX®), or random (POSIX).

Check Information

Group:Standard Libraries
Category: Required
AGC Category: Required

Version History

Introduced in R2024a