Main Content

Errno not reset

errno not reset before calling a function that sets errno

Description

This defect occurs when you do not reset errno before calling a function that sets errno to indicate error conditions. However, you check errno for those error conditions after the function call.

Risk

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.

Fix

Before calling a function that sets errno to indicate error conditions, reset errno to zero explicitly.

Examples

expand all

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

#define fatal_error() abort()

double func(const char *s1, const char *s2)
{
    double f1;
    f1 =  strtod (s1, NULL);      
    if (0 == errno) {        
      double f2 = strtod (s2, NULL); 
        if (0 == errno) {        
            long double result = (long double)f1 + f2;
            if ((result <= (long double)DBL_MAX) && (result >= (long double)-DBL_MAX)) 
				  {
                return (double)result;
            }
        }
    }
    fatal_error();
    return 0.0;
}

In this example, errno is not reset to 0 before the first call to strtod. Checking errno for 0 later can lead to a false positive.

Correction — Reset errno Before Call

One possible correction is to reset errno to 0 before calling strtod.

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

#define fatal_error() abort()

double func(const char *s1, const char *s2)
{
    double f1;
    errno = 0;                   
    f1 = strtod (s1, NULL);
    if (0 == errno) {            
      double f2 = strtod (s2, NULL);  
        if (0 == errno) {       
            long double result = (long double)f1 + f2;
            if ((result <= (long double)DBL_MAX) && (result >= (long double)-DBL_MAX)) 
  			{
                return (double)result;
            }
        }
    }
    fatal_error();
    return 0.0;
}

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: MISSING_ERRNO_RESET
Impact: High

Version History

Introduced in R2017a

expand all