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

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.

Polyspace Implementation

Polyspace® reports a violation of this rule if your code calls an errno-setting function but does not test errno against zero before calling another function.

Polyspace reports violations of this rule only for the functions that the C standard specifies as errno-setting function.

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


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.