CERT.FIO.NO_FLUSH

Flush or positioning function call missing

When alternately inputting and outputting from a stream, there should be an intervening call to a flush of file positioning function (fflush, fseek, fsetpos, or rewind).

Vulnerability and risk

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(), can lead to undefined behavior.

Mitigation and prevention

Add an intervening flush or positioning function call when input from stream is directly followed by output to a stream or vice versa.

Vulnerable code example

Copy
   #include <cstdio>
   void func(const char *file_name) {
   char buffer[500];
   char w_data[500];
     FILE *file = fopen(file_name, "a + ");
     fread(buffer, 1, 100, file);
     fwrite(w_data, 1, 100, file); //@ CERT.FIO.NO_FLUSH
     fclose(file);
   }

In this noncompliant example, no positioning function call is present between fread and fwrite; therefore, Klocwork reports a CERT.FIO.NO_FLUSH defect at line 7, when fwrite is called.

Fixed code example

Copy
   #include <cstdio>
   void func(const char *file_name) {
   char buffer[500];
   char w_data[500];
     FILE *file = fopen(file_name, "a + ");
     fread(buffer, 1, 100, file);
     fseek(file, 0L, SEEK_SET);
     fwrite(w_data, 1, 100, file);  //@no CERT.FIO.NO_FLUSH
     fclose(file);
  }

In this fixed example, fseek is called between fread and fwrite; therefore, Klocwork does not report a defect.