Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Minor edits; reviewed

...

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);
  }
}

Note that this code first sets errno to 0 to comply with ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure

...

Code Block
bgColor#ccccff
langc
#define __STDC_WANT_LIB_EXT1__ 1
#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[BUFSIZ64];
    if (strerror_s(errmsg, BUFSIZsizeof(errmsg), errno) != 0) {
      /* Handle error */
    }
    printf("Could not get the file position because of %s\n",
           errmsg);
  }
}

Note that because of the optional nature of Annex K, strerror_s() may not be available in all implementations. 

...

Code Block
bgColor#ccccff
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[BUFSIZ64];
    if (strerror_r(errno, errmsg, BUFSIZsizeof(errmsg)) != 0) {
      /* Handle error */
    }
    printf("Could not get the file position because of %s\n",
           errmsg);
  }
}

Note that Linux provides two versions of strerror_r(), known as the XSI-compliant version and the GNU-specific version. This compliant solution assumes the XSI-compliant version. You can get the XSI-compliant version if you compile applications in the way POSIX requires (that is, by defining _POSIX_C_SOURCE or _XOPEN_SOURCE appropriately). Check your strerror_r() manual page to see which version(s) are available on your system.

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

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

Related Guidelines

...

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

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

...