Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits

...

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 subclause 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.

Code Block
bgColor#FFCCCC
langc
#include <errno.h>
#include <stdio.h>
#include <string.h>
 
void f(FILE *fp) {
  fpos_t pos;
  errno = 0;

  if (0 != fgetpos(fp, &pos)) {
    char *errmsg = strerror(errno);
    printf("Could not get the file position because of %s\n",
           errmsg);
  }
}

...

Code Block
bgColor#ccccff
langc
#define __STDC_WANT_LIB_EXT1__ 1
#include <errno.h>
#include <stdio.h>
#include <string.h>
 
enum { BUFFERSIZE = 64 };
void f(FILE *fp) {
  fpos_t pos;
  errno = 0;

  if (0 != fgetpos(fp, &pos)) {
    char errmsg[64BUFFERSIZE];
    if (strerror_s(errmsg, sizeof(errmsg)BUFFERSIZE, errno) != 0) {
      /* Handle error */
    }
    printf("Could not get the file position because of %s\n",
           errmsg);
  }
}

...

Code Block
bgColor#ccccff
langc
#include <errno.h>
#include <stdio.h>
#include <string.h>
 
enum { BUFFERSIZE = 64 };
 
void f(FILE *fp) {
  fpos_t pos;
  errno = 0;

  if (0 != fgetpos(fp, &pos)) {
    char errmsg[64BUFFERSIZE];
    if (strerror_r(errno, errmsg, sizeof(errmsg)BUFFERSIZE) != 0) {
      /* Handle error */
    }
    printf("Could not get the file position because of %s\n",
           errmsg);
  }
}

...

[Historical information about POSIX.1 Thread Safety]Section 2.9.1
[ISO/IEC 9899:2011]

Section Subclause 7.24.6.2, "The strerror Function"
Annex K.3.7.4.2, "The strerror_s Function

...