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

1   #include <cstring>
2   #include <wchar.h>
3   #include <iostream>
4  
5   typedef FILE file4;
6   typedef file4 file3;
7   typedef file3 file2;
8   typedef file2 file;
9   file *pf1;
10 
11  #define FILE_ALIAS FILE
12  FILE_ALIAS *pf2;
13 
14  typedef FILE *file_pointer;
15  file_pointer pf3;
16 
17  typedef int *int_alias2;
18  typedef int_alias2 int_alias1;
19  typedef int_alias1 int_alias;
20  int_alias pf4;
21  
22  void func5_memcpy_function ( void )
23  {
24      memset((void *)pf1, '-', 0);      
25      memset((void *)pf2, '-', 0);      
26      wmemset((void *)pf3, '-', 0);     
27      memset((void *)pf4, '-', 0);      
28     
29      memset((void*)pf1, '-', 9);      
30      memset((void *)pf2, '-', 9);      
31      memset((void *)pf4, '-', 9);      
32  }

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

1   #include <cstring>
2   #include <wchar.h>
3   #include <iostream>
4  
5   typedef FILE file4;
6   typedef file4 file3;
7   typedef file3 file2;
8   typedef file2 file;
9   file pf1;
10 
11  #define FILE_ALIAS FILE
12  FILE_ALIAS pf2;
13 
14  typedef FILE file_pointer;
15  file_pointer pf3;
16 
17  typedef int *int_alias2;
18  typedef int_alias2 int_alias1;
19  typedef int_alias1 int_alias;
20  int_alias pf4;
21 
22  void func5_memcpy_function ( void )
23  {
24      memset((void *)pf1, '-', 0);      
25      memset((void *)pf2, '-', 0);      
26      wmemset((void *)pf3, '-', 0);     
27      memset((void *)pf4, '-', 0);      
28      memset((void *)pf4, '-', 9);     
29  }

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