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 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());
}
In this noncompliant example, Klocwork reports a defect CERT.FILE_PTR.DEREF.RETURN on lines 19, 20, and 21 because dereferencing a pointer to a FILE object that is returned by a function may result in unexpected behaviour.
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 )
{
FILE file2 = *((FILE*)getInt());
}
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