CERT.FILE_PTR.DEREF.INDIRECT

A pointer to a FILE object shall not be indirectly dereferenced by a system function, for example, by a call to memcpy or memcmp.

Vulnerability and risk

An indirect dereference of a pointer to a FILE object by a system function, for example, by a call to memcpy or memcmp, may result in unexpected behavior.

Mitigation and prevention

Do not dereference a pointer to a FILE object indirectly by using a system function.

Vulnerable code example

Copy
   #include <cstring>
   #include <wchar.h>
   #include <iostream>
  
   typedef FILE file4;
   typedef file4 file3;
   typedef file3 file2;
   typedef file2 file;
   file *pf1;
 
  #define FILE_ALIAS FILE
  FILE_ALIAS *pf2;
 
  typedef FILE *file_pointer;
  file_pointer pf3;
 
  typedef int *int_alias2;
  typedef int_alias2 int_alias1;
  typedef int_alias1 int_alias;
  int_alias pf4;
  
  void func5_memcpy_function ( void )
  {
      memset((void *)pf1, '-', 0);      
      memset((void *)pf2, '-', 0);      
      wmemset((void *)pf3, '-', 0);     
      memset((void *)pf4, '-', 0);      
     
      memset((void*)pf1, '-', 9);      
      memset((void *)pf2, '-', 9);      
      memset((void *)pf4, '-', 9);      
  }

In this noncompliant example, Klocwork reports a CERT.FILE_PTR.DEREF.INDIRECT on lines 30 and 31, because indirectly dereferencing a pointer to a FILE object by using a system function ‘memcpy’, may result in unexpected behavior.

Fixed code example

Copy
   #include <cstring>
   #include <wchar.h>
   #include <iostream>
  
   typedef FILE file4;
   typedef file4 file3;
   typedef file3 file2;
   typedef file2 file;
   file pf1;
 
  #define FILE_ALIAS FILE
  FILE_ALIAS pf2;
 
  typedef FILE file_pointer;
  file_pointer pf3;
 
  typedef int *int_alias2;
  typedef int_alias2 int_alias1;
  typedef int_alias1 int_alias;
  int_alias pf4;
 
  void func5_memcpy_function ( void )
  {
      memset((void *)pf1, '-', 0);      
      memset((void *)pf2, '-', 0);      
      wmemset((void *)pf3, '-', 0);     
      memset((void *)pf4, '-', 0);      
      memset((void *)pf4, '-', 9);     
  }

The above example is compliant because no system function is used to dereference a pointer to a FILE object.

Related checkers

  • MISRA.FILE_PTR.DEREF.INDIRECT.2012

External guidance