Section 7.21.5.3 of C11 the C Standard [ISO/IEC 9899:2011] places the following restrictions on update streams:
...
Code Block | ||||
---|---|---|---|---|
| ||||
char data[BUFFERSIZE]; char append_data[BUFFERSIZE]; char *file_name; FILE *file; /* Initialize file_name */ file = fopen(file_name, "a+"); if (file == NULL) { /* Handle error */ } /* initializeInitialize append_data */ if (fwrite(append_data, BUFFERSIZE, 1, file) != BUFFERSIZE) { /* Handle error */ } if (fread(data, BUFFERSIZE, 1, file) != 0) { /* Handle there not being data */ } fclose(file); |
However, because the stream is not flushed in between the call to fread()
and fwrite()
, the behavior is undefined.
...
In this compliant solution, fseek()
is called in between the output and input, eliminating the undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
char data[BUFFERSIZE]; char append_data[BUFFERSIZE]; char *file_name; FILE *file; /* initializeInitialize file_name */ file = fopen(file_name, "a+"); if (file == NULL) { /* Handle error */ } /* Initialize append_data */ 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) { /* Handle there not being data */ } fclose(file); |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE | Fortify SCA | V. 5.0 | Can detect simple violations of this rule with CERT C Rule Pack. | Compass/ROSE | |||||
Fortify SCA | 5.0 | Can detect simple violations of this rule with CERT C Rule Pack. | |||||||
| 84 D | Fully implemented. |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
ISO/IEC TS 17961 (Draft) | Interleaving stream inputs and outputs without a flush or positioning call [ioileave] |
Bibliography
[ISO/IEC 9899:2011] | Section 7.21.5.3, "The fopen Function" |
...