CertC++-FIO44¶
Only use values for fsetpos() that are returned from fgetpos()
Required inputs: IR
The C Standard, 7.23.9.3 paragraph 2 [ ISO/IEC 9899:2024 ], defines the following behavior for fsetpos() :
The
fsetposfunction sets thembstate_tobject (if any) and file position indicator for the stream pointed to bystreamaccording to the value of the object pointed to bypos, which shall be a value obtained from an earlier successful call to thefgetposfunction on a stream associated with the same file.
Invoking the fsetpos() function with any other values for pos is undefined behavior 181 .
Noncompliant Code Example
This noncompliant code example attempts to read three values from a file and then set the file position pointer back to the beginning of the file:
#include <stdio.h>
#include <string.h>
int opener(FILE *file) {
int rc;
fpos_t offset;
memset(&offset, 0, sizeof(offset));
if (file == NULL) {
return -1;
}
/* Read in data from file */
rc = fsetpos(file, &offset);
if (rc != 0 ) {
return rc;
}
return 0;
}
|
Only the return value of an fgetpos() call is a valid argument to fsetpos() ; passing a value of type fpos_t that was created in any other way is undefined behavior 181 .
Compliant Solution
In this compliant solution, the initial file position indicator is stored by first calling fgetpos() , which is used to restore the state to the beginning of the file in the later call to fsetpos() :
#include <stdio.h>
#include <string.h>
int opener(FILE *file) {
int rc;
fpos_t offset;
if (file == NULL) {
return -1;
}
rc = fgetpos(file, &offset);
if (rc != 0 ) {
return rc;
}
/* Read in data from file */
rc = fsetpos(file, &offset);
if (rc != 0 ) {
return rc;
}
return 0;
}
|
Risk Assessment
Misuse of the fsetpos() function can position a file position indicator to an unintended location in the file.
| Rule | Severity | Likelihood | Detectable | Repairable | Priority | Level |
|---|---|---|---|---|---|---|
| FIO44-C | Medium | Unlikely | No | No | P2 | L3 |
Related Guidelines
| Taxonomy | Taxonomy item | Relationship |
| ISO/IEC TS 17961:2013 | Using a value for fsetpos other than a value returned from fgetpos [xfilepos] | Prior to 2018-01-12: CERT: Unspecified Relationship |
Bibliography
| [ ISO/IEC 9899:2024 ] | 7.23.9.3, "The fsetpos Function" |
Possible Messages
Key |
Text |
Severity |
Disabled |
|---|---|---|---|
fsetpos_not_from_fgetpos |
Only use values for fsetpos() that are returned from fgetpos(). |
None |
False |
Options
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
This rule has no individual options.