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

1   #include <iostream>
2
3   typedef FILE file4;
4   typedef file4 file3;
5   typedef file3 file2;
6   typedef file2 file;
7  
8   #define FILE_ALIAS FILE
9  
10  void func13_cast_to_file_pointer(void *p)
11  {
12     FILE file_a;
13     file_a = *((FILE *) p);        
14     file_a = *((file *) p);        
15     file_a = *((FILE_ALIAS *) p);
16  }  

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

1   #include <iostream>
2  
3   typedef FILE file4;
4   typedef file4 file3;
5   typedef file3 file2;
6   typedef file2 file;
7  
8   #define FILE_ALIAS FILE
9
10  void func13_cast_to_file_pointer (void *p)
11  {
12      FILE *file_a;
13      file_a = ((FILE *) p);                 
14      file_a = ((file *) p);                   
15      file_a = ((FILE_ALIAS *) p);     
16  }

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