Versions Compared

Key

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

According to The N1401-C1X document section 7.21.2.1 states,

The rand function is not required to avoid data races.

Similarly, the following library functions are also not required to avoid data races

...

Multiple threads invoking the same function can cause concurrency problems. Concurrency problems can often result in abnormal behavior, but it is possible for them to result in more serious vulnerabilities. 

Non Compliant Code

Consider a multithreaded application which involves a function which returns a random value each time it is invoked. If two threads concurrently invoke the rand() function, it may result in undefined behavior and may also result in rand() returning the same value in both the threads.

Code Block
bgColor#FFCCCC

int get_secret() {

    int secret = (rand() % 100) + 100;
    return secret;
}

Compliant Solution

The compliant solution uses a mutex to make each call to rand() library function atomic

Code Block
bgColor#ccccff

#include <pthread.h>

pthread_mutex_t rand_lock = PTHREAD_MUTEX_INITIALIZER;

int get_secret() {
    int secret;

    pthread_mutex_lock(&rand_lock) ;
    secret = (rand() % 100) + 100;
    pthread_mutex_unlock(&rand_lock);

    return secret;
}

Risk Assessment

Race conditions caused by multiple threads invoking the same library function can lead to abnormal termination or may lead to data integrity violations

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

POS04-C

medium

probable

High

P4

L3

References

[N1401-C1X Draft Standard] Section 7.21.2.1 rand() function, Section 7.21.4.6 getenv() function, Section 7.22.5.8 strtok() function, Section 7.22.6.2 strerror() function, Section 7.25.3.1 asctime() function, Section 7.25.3.2 ctime() function