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

Compare with Current View Page History

« Previous Version 13 Next »

Receiving input from a stream directly following an output to that stream without an intervening call to fflush(), fseek(), fsetpos(), or rewind() results in undefined behavior. Therefore, a call to one of these functions is necessary in between input and output to the same update 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.

/* some device used for both input and output */
const char *filename = "/dev/device2";

FILE *file = fopen(filename, "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.

/* some device used for both input and output */
const char *filename = "/dev/device2";

FILE *file = fopen(filename, "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

2 (medium)

2 (probable)

2 (medium)

P8

L2

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