Versions Compared

Key

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

...

According to the C Standard [ISO/IEC 9899:2011], the following library functions are not required to avoid data races:

  • rand()
  • getenv()
  • strtok()
  • strerror()
  • asctime()
  • ctime()

Section 2.9.1 of the System Interfaces volume of POSIX.1-2008 has a much longer list of functions that are not required to be thread-safe.

...

Consider a multithreaded application that encounters an error while calling a system function. The strerror() function returns a human-readable error string given an error number. The C Standard, section 7.24.6.2 [ISO/IEC 9899:2011], specifically states that strerror() is not required to avoid data races. Conventionally, it could rely on a static array that maps error numbers to error strings, and that array might be accessible and modifiable by other threads. (This code is specific to POSIX because fopen() is not guaranteed to set errno if an error occurs in C99 or C11.)

...

This compliant solution uses the strerror_s() function from Annex K of the C Standard, which has the same functionality as strerror() but guarantees thread-safety. Furthermore, in C11C, errno is a thread-local variable, so there is no race condition between when the time it is initialized and the time it is read by strerror_s().

Code Block
bgColor#ccccff
langc
errno = 0;
FILE* fd = fopen( filename, "r");
if (fd == NULL) {
  char errmsg[BUFSIZ];
  if (strerror_s(errno, errmsg, BUFSIZ) != 0) {
    /* handle error */
  }
  printf("Could not open file because of %s\n", errmsg);
}

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

A module written in Compass/ROSE can detect violations of this rule.

Related Guidelines

...

...

Bibliography

ISO/IEC 9899:2011 Section 7.22.2.1, "The rand function," Section 7.22.4.6, "The getenv function," Section 7.24.5.8, "The strtok function," Section 7.24.6.2, "The strerror function," Section 7.27.3.1, "The asctime function," Section 7.27.3.2, "The ctime function"

Sources

...

...

 Section

...

7.

...

24.

...

6.

...

2, "The strerror

...

Function"