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.

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.

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