CERT.FILE_PTR.DEREF.RETURN

A pointer to a FILE object (returned by function) shall not be dereferenced.

Vulnerability and risk

Dereferencing the pointer to a FILE object that is returned by a function may result in unexpected behavior.

Mitigation and prevention

Do not dereference a pointer to a FILE object that is returned by a function.

Vulnerable code example

Copy
   #include <cstring>

   typedef FILE file4;
   typedef file4 file3;
   typedef file3 file2;
   typedef file2 file;
  
   #define FILE_ALIAS FILE
  
  void func13_cast_to_file_pointer(void *p)
  {
     FILE file_a;
     file_a = *((FILE *) p);        
     file_a = *((file *) p);        
     file_a = *((FILE_ALIAS *) p);
  }

In this noncompliant example, Klocwork reports a CERT.FILE_PTR.DEREF.CAST defect on Lines 13, 14, and 15, because dereferencing a object that is casted to a FILE pointer may result in unexpected behavior.

Fixed code example

Copy
   #include <cstring>
  
   typedef struct __sFILE {
       int pos;
   } FILE;
  
   FILE *getFile() {
       FILE *p;
       return p;
  }
  
  static int i = 1;
  int *getInt() {
      return &i;
  }
  
  void func9_function_return ( void )
  {
      int x = getFile()->pos;           
      FILE file1 = *getFile();          
      char chr = *((char*)getFile());   
  }

The above example is compliant because no code dereferences a pointer to a FILE object that is returned by a function.

Related checkers

  • MISRA.FILE_PTR.DEREF.RETURN.2012

External guidance