You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 20 Next »

Receiving input from a stream directly following an output to that stream (or vice versa) without an intervening call to fflush(), fseek(), fsetpos(), or rewind() results in undefined behavior. Consequently a call to one of these functions is necessary in between input and output to the same stream.

Non-Compliant Code Example

In this non-compliant code example, a device is opened for updating, data are sent to it, and then the response is read back.

FILE *file = fopen(file_name, "rb+");
if (file == NULL) {
  /* handle error */
}

/* write to file stream */
/* read response from file stream */
fclose(file);

However, the output buffer is not flushed before receiving input back from the stream, so the data may not have actually been sent, resulting in unexpected behavior.

Compliant Solution

In this compliant solution, fflush() is called in between the output and input.

FILE *file = fopen(file_name, "rb+");
if (file == NULL) {
  /* handle error */
]

/* write to file stream */
fflush(file);
/* read response from file stream */
fclose(file);

This flush ensures that all data has been cleared from the buffer before continuing.

Risk Assessment

Failing to flush the output buffer may result in data not being sent over the stream, causing unexpected program behavior and possibly a data integrity violation.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO39-C

medium

probable

medium

P8

L2

Automated Detection

Fortify SCA Version 5.0 with CERT C Rule Pack can detect violations of this rule.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[ISO/IEC 9899:1999]] Section 7.9.15.3, "The fopen function"


FIO38-C. Do not use a copy of a FILE object for input and output      09. Input Output (FIO)       FIO40-C. Reset strings on fgets() failure

  • No labels