Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Rule MSC30-C. Do not use the rand() function for generating pseudorandom numbers addresses RNGs from a different perspective, i.e. the time till first collision occurs. In other words, during a single run of an RNG, the time interval after which, the RNG generates the same random numbers. The rule MSC30-C deprecates the rand() function as it generates numbers which have a comparatively short cycle. The same rule proposes the use of random() function for POSIX and CryptGenRandom() function for Windows.

The current rule (MSC32-C) examines these three RNGs in terms of seeding. Noncompliant code examples correspond to the use of an RNG without a seed, while compliant solutions correspond to the same RNG being properly seeded. Rule MSC32-C addresses all three RNGs mentioned in rule MSC30-C for completeness. Rule MSC32-C complies to MSC30-C and does not recommend the use of the rand() function. Nevertheless, if it is unavoidable to use rand(), at least, it should be properly seeded.

...

Code Block
bgColor#ccccff
srandom(time(NULL)); /* Create seed based on current time counted as seconds from 01/01/1970 */
int i=0;
for (i=0; i<10; i++) {
    printf("%d, ", random()); /* Generates different sequences at different runs */
}

output:
1st run: 198682410, 2076262355, 910374899, 428635843, 2084827500, 1558698420, 4459146, 733695321, 2044378618, 1649046624,
2nd run: 1127071427, 252907983, 1358798372, 2101446505, 1514711759, 229790273, 954268511, 1116446419, 368192457, 1297948050,
3rd run: 2052868434, 1645663878, 731874735, 1624006793, 938447420, 1046134947, 1901136083, 418123888, 836428296, 2017467418,
...

In the previous examples, seeding in rand() and random() is done using the time() function, which returns the current time calculated as the number of seconds that have past since 01/01/1970. Depending on the application and the desirable level of security, a programmer may choose alternative ways to seed RNGs. In general, hardware is more capable of generating real random numbers (for example generate a sequence of bits by sampling the thermal noise of a diode and use this as a seed).

Compliant Solution (Windows)

Wiki Markup
[{{CryptGenRandom()}}|http://msdn.microsoft.com/en-us/library/aa379942.aspx] does not run the risk of not being properly seeded. The reason for that is that its arguments serve as seeders. From the Microsoft Developer Network {{CryptGenRandom()}} reference \[MSDN\]:

...