Main Content

MISRA C:2012 Rule 22.9

The value of errno shall be tested against zero after calling an errno-setting function

Description

Rule Definition

The value of errno shall be tested against zero after calling an errno-setting function.

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

Rationale

If an error occurs during a call to an errno-setting-function, the function writes a nonzero value to errno. Otherwise, errno is not modified.

When errno is nonzero, the function return value is not likely to be correct. Before using this return value, you must test errno for nonzero values.

Errno-setting functions include:

  • ftell, fgetpos, fgetwc and related functions.

  • strtoimax, strtol and related functions.

    The wide-character equivalents such as wcstoimax and wcstol are also covered.

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 <stdlib.h>
#include <errno.h>

void func(void);
double val = 0.0;

void f1 ( void )
{
  errno = 0;
  val = strtod ( "1.0", NULL ); /* Non-compliant */
  func ();

  if ( 0 != errno )
    {
    }

  errno = 0;
  val = strtod ( "1.0", NULL ); /* Compliant */
  if ( 0 == errno ) 
    {
      func();
    }
}

In this example, the rule is violated when errno is not checked immediately after the first call to strtod. Instead, a second function func is called. func might use the value in the global variable val. The value can be incorrect if an error has occurred during the call to strtod.

The rule is not violated when errno is checked before operations that potentially use the return value of strtod.

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2017a