Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The C++ Standard, [filebuf], paragraph 2, states [ISO/IEC 14882-2014]:

The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf<charT, traits> are the same as for reading and writing with the Standard C library FILEs.

The C Standard, 7.19 7.21.5.3, paragraph 7 6, places the following restrictions on FILE objects opened for both reading and writing [ISO/IEC 9899:2011], places the following restrictions on update streams1999]:

When a file is opened with update mode . . ., both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the the fflush function  function or to a file positioning function (fseek, fsetpos, or or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.

 

Thus, the The following scenarios can result in undefined behavior (see undefined behavior 151):

  •  Receiving input from a stream directly following an output to that stream without an intervening call to fflush(), fseek(), fsetpos(), or rewind() if std::basic_filebuf<T>::seekoff() if the file is not at end-of-file
  •  Outputting to a stream after receiving input from that stream without a call to fseek(), fsetpos(), or rewind() if std::basic_filebuf<T>::seekoff() if the file is not at end-of-file

Consequently, No other std::basic_filebuf<T> function guarantees behavior as if a call to fseek(), fflush(), or fsetpos() is necessary between input and output to the same stream. See FIO07-CPP. Prefer fseek() to rewind() for more information on why fseek() is preferred over rewind()were made to a Standard C library file positioning function, or std::fflush().

Note that calling std::basic_ostream<T>::seekp() or std::basic_istream<T>::seekg() eventually results in a call to std::basic_filebuf<T>::seekoff() for file stream positioning. Given that std::basic_iostream<T> inherits from both std::basic_ostream<T> and std::basic_istream<T>, and std::fstream inherits from std::basic_iostream, either function is acceptable to call to ensure the file buffer is in a valid state prior to the subsequent IO operation.

Noncompliant Code Example

This noncompliant code example appends data to the end of a file, and then reads from the same file. However, because there is no intervening positioning call between the formatted output and input calls, the behavior is undefined.

Code Block
bgColor#ffcccc
langcpp
#include <stdio.h><fstream>
 
enum { BUFFERSIZE = 32 };

extern void initialize_data(char *data, size_t size);
 
void func(const char *file_name#include <string>

void f(const std::string &N) {
  char data[BUFFERSIZE];
  char append_data[BUFFERSIZE];
  FILE *file;

  file = fopen(file_name, "a+"std::fstream f(N);
  if (file == NULL!f.is_open()) {
    /*/ Handle error */
  }
 
  initialize_data(append_data, BUFFERSIZE);

  if (fwrite(append_data, 1, BUFFERSIZE, file) != BUFFERSIZE) {
    /* Handle error */
  }
  if (fread(data, 1, BUFFERSIZE, file) < BUFFERSIZE) {
    /* Handle there not being data */
  }

  if (fclose(file) == EOF) {
    /* Handle error */
  }
}

...

return;
  }
  
  f << "Output some data";
  std::string str;
  f >> str;
}

Compliant Solution

In this compliant solution, fseekthe std::basic_istream<T>::seekg() function is called in between the output and input, eliminating the undefined behavior.

Code Block
bgColor#ccccff
langcpp
#include <stdio.h><fstream>
#include 
enum { BUFFERSIZE = 32 };
extern void initialize_data(char *data, size_t size);
 
void func(const char *file_name<string>

void f(const std::string &N) {
  char data[BUFFERSIZE];
  char append_data[BUFFERSIZE];
  FILE *file;

  file = fopen(file_name, "a+"std::fstream f(N);
  if (file == NULL) {
    /* Handle error */
  }

  initialize_data(append_data, BUFFERSIZE);
  if (fwrite(append_data, BUFFERSIZE, 1, file) != BUFFERSIZE) {
    /* Handle error */
  }

  if (fseek(file, 0L, SEEK_SET) != 0) {
    /* Handle error */
  }

  if (fread(data, BUFFERSIZE, 1, file) != 0!f.is_open()) {
    /* Handle there not being data */
  }

  if (fclose(file) == EOF) {
    /* Handle error */
  }
}

Noncompliant Code Example (iofstream)

This noncompliant code example uses C++ iostreams, but makes the same mistake as the previous noncompliant code example.

Code Block
bgColor#ffcccc
langcpp
{
  char data[BUFFERSIZE];
  char append_data[BUFFERSIZE] return;
  char *file_name;

  // Initialize file_name and append_data }
  
  fstream file( file_name, fstream::in | fstream::out | fstream::app);
  file << append_data << ends;
  file >> data;
  // ...
} // File gets closed here

Compliant Solution (seekg)

In this compliant solution, the seekg() member function is called in between the output and input, eliminating the undefined behavior.

Code Block
bgColor#ccccff
langcpp
{
  char data[BUFFERSIZE];
  char append_data[BUFFERSIZE];
  char *file_name;

  // Initialize file_name and append_data
  fstream file( file_name, fstream::in | fstream::out | fstream::app);
  file << append_data << ends;
	filef << "Output some data";
 
  std::string str;
  f.seekg(0, std::ios::beg);
  filef >> data;
  // ...
} // File gets closed herestr;
}

Risk Assessment

Alternately inputting and outputting from a stream without an intervening flush or positioning call is undefined behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO39-CPP

Low

Likely

Medium

P6

L2

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE 

 

 

Can detect simple violations of this rule

Fortify SCA

5.0

 

Can detect violations of this rule with CERT C Rule Pack

LDRA tool suite

Include Page
LDRA_VLDRA_V

84 D

Fully implemented

Related Vulnerabilities

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

Related Guidelines

Bibliography

TS 17961:2013
[ISO/IEC Interleaving stream inputs and outputs without a flush or positioning call [ioileave]

...

14882-2014]Clause 27, "Input/Output Library"
[ISO/IEC 9899:20111999]7.2119.5.3, "The fopen Function"

 

...