Main Content

MISRA C:2012 Rule 22.10

The value of errno shall only be tested when the last function to be called was an errno-setting function

Description

Rule Definition

The value of errno shall only be tested when the last function to be called was an errno-setting function.

This rule comes from MISRA C™: 2012 Amendment 1.

Rationale

Besides the errno-setting functions, the Standard does not enforce that other functions set errno on errors. Whether these functions set errno or not is implementation-dependent.

To detect errors, if you check errno alone, the validity of this check also becomes implementation-dependent. On implementations that do not require errno setting, even if you check errno alone, you can overlook error conditions.

For a list of errno-setting functions, see MISRA C:2012 Rule 22.8.

For information on how to detect errors, see the documentation for that specific function.

Typically, the functions return an out-of-band error indicator to indicate errors. For instance:

  • fopen returns a null pointer if an error occurs.

  • signal returns the SIG_ERR error indicator and sets errno to a positive value. Check errno only after you have checked the function return value.

Polyspace Implementation

Polyspace® raises a violation of this rule when you check errno for error conditions in situations where checking errno does not guarantee the absence of errors. In some cases, checking errno can lead to false positives.

For instance, you check errno following calls to the functions:

  • fopen: If you follow the ISO® Standard, the function might not set errno on errors.

  • atof: If you follow the ISO Standard, the function does not set errno.

  • signal: The errno value indicates an error only if the function returns the SIG_ERR error indicator.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <stddef.h>
#include <stdlib.h>

typedef double float64_t;

void f(void)
{
    float64_t f64;
    errno = 0;
    f64 = atof("A.12");
    if (0 == errno) { /* Non-compliant */
    }
    errno = 0;
    f64 = strtod("A.12", NULL);
    if (0 == errno) { /* Compliant */
    }
}

In this example:

  • The first if statement is noncompliant because atof may or may not set errno when an error is detected. f64 may not have a valid value within this if statement.

  • The second if statement is compliant because strtod is an errno-setting function. f64 will have a valid value within this if statement.

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2017a