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

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.

If you do not explicitly set errno to zero before a function call, it can contain values from a previous call. Checking errno for nonzero values after the function call can give the false impression that an error occurred.

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 Coding Standard Violations Not Displayed.

Examples

expand all

#include <stdlib.h>
#include <errno.h>

double val = 0.0;

void f ( void )
{
    val = strtod("1.0",NULL);/*errno is not checked*/ 
    if ( 0 == errno ) /* Non-compliant*/
    {
        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
Introduced in R2017a