Qt-Autosar-A26.5.1

Pseudorandom numbers shall not be generated using std::rand()

Required inputs: IR

Rationale

Using a pseudo-random sequence of numbers requires that it is generated with good statistical properties. Some implementations of std::rand() function have a comparatively short cycle, as a result the numbers can be predictable. Using functionalities from <random> is recommended instead of using std::rand().

Note: std::random_shuffle should not be used, as it is deprecated since C++14 (see A1-1-1) and one of the available overloads is often implemented in terms of std::rand.

Example
// $Id: A26-5-1.cpp 311495 2018-03-13 13:02:54Z michal.szczepankiewicz $

    #include     <cstdlib>
    #include     <cstdint>
    #include     <ctime>
    #include     <iostream>
    #include     <random>

    int main()
    {
        std::srand(std::time(nullptr));
        int r1 = std::rand() % 100; //non-compliant
        std::cout << "Random value using std::rand(): " << r1 << std::endl;

         std::random_device rd;
         std::default_random_engine eng{rd()};
         std::uniform_int_distribution<int> ud{0, 100};
         int r2 = ud(eng); //compliant
         std::cout << "Random value using std::random_device: " << r2 << std::endl;

         return 0;
    }
See Also
  • SEI CERT C++ Coding Standard [10]: MSC50-CPP: Do not use std::rand() for generating pseudorandom numbers.

Possible Messages

Key

Text

Severity

Disabled

forbidden_libfunc_call

Call to forbidden function.

None

False

Options

blacklist

blacklist

Type: dict[bauhaus.analysis.config.FileGlobPattern, list[bauhaus.analysis.config.GlobPattern]]

Default:

{
   '*stdlib.h': ['rand']
}
Dictionary of header globbing to (list of) function name globbing(s) of forbidden functions.