You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Calling rand() function several times to produce a sequence of pseudorandom numbers will result in generating the same sequence in different runs of the program.

This can lead to security threat since, after the first run, an attacker will know the sequence to be generated.

Noncompliant Code Example

 The following code generates a sequence of 10 pseudorandom numbers. No matter how many times this code is executed, it always produces the same sequence.

for (int i=0; i<10; i++)
{
    cout<<rand()<<endl; /* Always generates the same sequence */
}

Compliant Solution

Use srand() before rand() to seed the random sequence generated by rand().

srand(time(NULL)); /* Create seed based on current time */

for (int i=0; i<10; i++)
{
    cout<<rand()<<endl; /* Generates different sequences at different runs */
}

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC18-C

 

likely

 

 

 

 Automated Detection

 TODO

Related Vulnerabilities

 TODO

Other Languages

This recommendation appears in the C Secure Coding Standard as MSC18C. Use srand() before rand() to generate different sequences of pseudorandom numbers.

References

C++Reference

  • No labels