CertC-FIO09

Be careful with binary data when transferring data across systems

Required inputs: IR

Portability is a concern when using the fread() and fwrite() functions across multiple, heterogeneous systems. In particular, it is never guaranteed that reading or writing of scalar data types such as integers, let alone aggregate types such as arrays or structures, will preserve the representation or value of the data. Implementations may differ in structure padding, floating-point model, number of bits per byte, endianness, and other attributes that cause binary data formats to be incompatible.

Noncompliant Code Example

This noncompliant code example reads data from a file stream into a data structure:

struct myData {
  char c;
  long l;
};

/* ... */

FILE *file;
struct myData data;

/* Initialize file */

if (fread(&data, sizeof(struct myData), 1, file) < sizeof(struct myData)) {
  /* Handle error */
}

However, the code makes assumptions about the layout of myData , which may be represented differently on a different platform.

Compliant Solution

The best solution is to use either a text representation or a special library that ensures data integrity:

struct myData {
  char c;
  long l;
};

/* ... */

FILE *file;
struct myData data;
char buf[25];
char *end_ptr;

/* Initialize file */

if (fgets(buf, 1, file) == NULL) {
  /* Handle error */
}

data.c = buf[0];

if (fgets(buf, sizeof(buf), file) == NULL) {
  /* Handle Error */
}

data.l = strtol(buf, &end_ptr, 10);

if ((ERANGE == errno)
 || (end_ptr == buf)
 || ('\n' != *end_ptr && '\0' != *end_ptr)) {
    /* Handle Error */
}
Risk Assessment

Reading binary data that has a different format than expected may result in unintended program behavior.

Recommendation Severity Likelihood Detectable Repairable Priority Level
FIO09-C Medium Probable No No P4 L3
Related Guidelines
SEI CERT C++ Coding Standard VOID FIO09-CPP. Be careful with binary data when transferring data across systems
Bibliography
[ Summit 1995 ] 20.5 on C-FAQ
Excerpt from SEI CERT C Coding Standard: Rules for Developing Safe, Reliable, and Secure Systems (2016 Edition) and SEI CERT C Coding Standard [https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/input-output-fio/fio09-c], Copyright (C) 1995-2026 Carnegie Mellon University. See 9.4 3rd-Party Licenses in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

possible_reading_binary_data

Be careful with binary data when transferring data across systems.

None

False

Options

read_functions

read_functions

Type: dict[bauhaus.analysis.config.QualifiedName, int]

Default:

{
   'fgets': 0,
   'fread': 0,
   'getline': 0,
   'read': 1,
   'recv': 1
}
I/O read functions mapped to the argument of output buffer argument.