AutosarC++18_03-A26.5.2¶
Random number engines shall not be default-initialized
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
Using a pseudo-random number generator gives different results that depend on a used seed value. Initializing random number engines by default initializes pseudo- random generator with a default_seed constant value. However, this can be not obvious for a developer and can lead to unexpected program behaviour (generating the same random sequences among different program executions).
Exceptions
For consistent testing purposes it can be convenient to seed the random number engine with a fixed value to get a deterministic sequence, but never within production code where real randomness is required, e.g. for security reasons.
Example
// $Id: A26-5-2.cpp 311495 2018-03-13 13:02:54Z michal.szczepankiewicz $
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::default_random_engine eng{rd()}; // compliant
std::uniform_int_distribution<int> ud{0, 100};
int r1 = ud(eng);
std::cout << "Random value using std::random_device: " << r1 << std::endl;
std::default_random_engine eng2{}; // non-compliant
std::uniform_int_distribution<int> ud2{0, 100};
int r2 = ud2(eng);
std::cout << "Random value using std::random_device: " << r2 << std::endl;
return 0;
}
See Also
- SEI CERT C++ Coding Standard [9]: MSC51-CPP: Ensure your random number generator is properly seeded.
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
forbidden_default_constructor_call |
Call to forbidden default constructor. |
None |
False |
Options¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
blacklist¶
blacklist
Set of forbidden class names where calling the default constructor is forbidden.Type: set[bauhaus.analysis.config.QualifiedName]
Default:
{'std::default_random_engine', 'std::knuth_b', 'std::linear_congruential_engine', 'std::mersenne_twister_engine', 'std::minstd_rand0', 'std::mt19937', 'std::mt19937_64', 'std::ranlux24', 'std::ranlux24_baset', 'std::ranlux48', 'std::ranlux48_base', 'std::subtract_with_carry_engine'}