CXX.ERRNO.INCORRECTLY_CHECKED

Errno condition check not required after calling library function

The CXX.ERRNO.INCORRECTLY_CHECKED checker flags cases where the errno value is checked after calling a library function that does not set its value.

Vulnerability and risk

The value of errno can be checked incorrectly after any previous call of library function. Checking an errno value after calling a library function that does not use it can lead to the incorrect execution of code.

Mitigation and prevention

Never inspect the value of errno after calling any library function that does not use errno.

Vulnerable code example 1

Copy
  #include <errno.h>
  #include <stdio.h>
  
  void func(const char *filename) {
    FILE *fileptr;
   
    fileptr = fopen(filename, "rb");
    if (errno != 0) {
      /* Handle error */
   }
 }

In this noncompliant example, the code may fail to diagnose errors because fopen() may not set the value of errno even if an error occurs.

Fixed code example 1

Copy
   #include <stdio.h>
     
   void func(const char *filename) {
     FILE *fileptr = fopen(filename, "rb");
     if (fileptr == NULL)  {
       /* An error occurred in fopen() */
     }
   }

The C Standard makes no mention of errno when describing fopen(). In this fixed example, the code uses the results of the call to fopen() to determine failure; the code does not check the value of errno.

Vulnerable code example 2

Copy
  #include <errno.h>
  #include <stdio.h>
    
  void func(const char *filename) {
    FILE *fileptr;
   
    errno = 0;
    fileptr = fopen(filename, "rb");
    if (errno != 0) {
     /* Handle error */
   }
 }

In this noncompliant example, the code may fail to diagnose errors because fopen() may not set the value of errno even if an error occurs.

Fixed code example 2

Copy
  #include <stdio.h>
    
  void func(const char *filename) {
    FILE *fileptr = fopen(filename, "rb");
    if (fileptr == NULL)  {
      /* An error occurred in fopen() */
    }
  }

The C Standard makes no mention of errno when describing fopen(). In this fixed example, the code uses the results of the call to fopen() to determine failure and does not check the value of errno.

Extension

This checker can be extended through the Klocwork knowledge base (KBs). See Tuning C/C++ analysis for more information.