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

The errno is not clean and can contain values from a previous call. Checking errno for errors can give the false impression that an error occurred.

errno is set to zero at program startup but subsequently, errno is not reset by a C standard library function. You must explicitly set errno to zero 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
CWE ID: 253, 456, 703
Introduced in R2017a