メインコンテンツ

MISRA C:2012 Rule 21.24

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

R2024a 以降

説明

ルール定義

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

This rule comes from MISRA C™:2012 Amendment 3.

根拠

rand() によって生成される数値は疑似乱数であり、srand() によって設定されるシードに依存します。そのため、rand() によって生成される数値は予測可能であり、暗号法的に脆弱です。コードでは乱数発生のシード値を設定しますが、シード値を使用することはないため、srand() 自体の使用は余分です。

Polyspace 実装

Polyspace® は、コードに rand() または srand() が含まれている場合は常にこのルールの違反を報告します。

トラブルシューティング

ルール違反を想定していてもその違反が表示されない場合、コーディング規約違反が想定どおりに表示されない理由の診断を参照します。

すべて展開する


#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;
}

この例では、rand() が乱数 nloops および i を生成します。Polyspace は rand() の両方の使用に対し、MISRA C:2012 Rule 21.24 の違反を報告します。CryptGenRandom (Windows®)、OpenSSL/RAND_bytes (Linux®/UNIX®)、random (POSIX) など、暗号法的により堅牢な疑似乱数 (PRNG) を使用してください。

チェック情報

グループ: 標準ライブラリ
カテゴリ: 必要
AGC カテゴリ: 必要

バージョン履歴

R2024a で導入


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.