CERT.FILE_PTR.DEREF.CAST

Object is casted to a FILE pointer, and it shall not be dereferenced.

Vulnerability and risk

Dereferencing an object that is casted to a FILE pointer may result in unexpected behavior.

Mitigation and prevention

Do not dereference an object that is casted to a FILE pointer.

Vulnerable code example

Copy
   #include <iostream>

   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 <iostream>
  
   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);     
  }

The above example is compliant because it uses the address of an object that is casted to File Pointer.

Related checkers

  • MISRA.FILE_PTR.DEREF.CAST.2012

External guidance