Main Content

MISRA C:2012 Rule 22.8

The value of errno shall be set to zero prior to a call to an errno-setting-function

Description

Rule Definition

The value of errno shall be set to zero prior to a call to an errno-setting-function.1

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

Rationale

An errno-setting function sets errno to nonzero values to indicate error conditions.

If you do not set errno to zero before calling an errno-setting function,a nonzero value of errno might be left over from a previous call to an errno-setting function. Using errno to check errors can then lead you to falsely conclude that an error occurred from the most recent call.

errno is set to 0 at program startup but is not automatically reset after an error occurs. You must explicitly set errno to 0 when required.

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 without taking either of these steps first:

  • Set errno to zero.

  • Compare errno to zero in a conditional statement and call the function in the branch where errno is zero.

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>

double val = 0.0;

void f ( void )
{
    val = strtod("1.0",NULL); /* Non-compliant*/ 
    if ( 0 == errno ) 
    {
        val = strtod("1.0",NULL); /* Compliant - case 1*/
        if ( 0 == errno ) /* Check errno for nonzero values */
        {
        }
    }
    else
    {
        errno = 0;
        val = strtod("1.0",NULL); /* Compliant - case 2*/
        if ( 0 == errno ) /* Check errno for nonzero values */
        {
        }
    }
}

In this example, the rule is violated when strtod is called but errno is not reset prior to the call.

The rule is not violated in the following cases:

  • Case 1: errno is compared against zero and then strtod is called in the if( 0 == errno ) branch.

  • Case 2: errno is explicitly set to zero and then strtod is called.

Check Information

Group: Resources
Category: Required
AGC Category: Required

Version History

Introduced in R2017a

expand all


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.