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

Compare with Current View Page History

« Previous Version 10 Next »

Portability is an important issue to keep in mind when using the fread() and fwrite() functions across multiple systems. In particular, it is never guaranteed that reading or writing of simple data structures such as int's, let alone complex structures such as float's or struct's, will preserve the representation or value of the data. Different compilers use different amounts of padding. Different machines use various floating point models and may use a different number of bits per byte. In addition, there is always the issue of endianness.

Non-compliant Code Example

struct {
    char c;
    float f;
} myData;

/* There is no way to verify what binary model was used to write the data */
fread(&myData, sizeof(myData), 1, fd);

Compliant Solution

The best solution is to use either a text representation or a special library that will ensure the integrity of data.

struct {
    char c;
    float f;
} myData;

if(fscanf(fd, "%c %f\n", &myData.c, &myData.f) != 2) {
    /* Handle error */
}

Risk Assessment

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

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

FIO09-A

low

unlikely

medium

P2

L3

Related Vulnerabilities

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

References

[[Summit 95]], 20.5 on C-FAQ


FIO08-A. Take care when calling remove() on an open file      09. Input Output (FIO)       FIO10-A. Take care when using the rename() function

  • No labels