...
| Code Block | ||
|---|---|---|
| ||
#include <stdio.h> char *buffer = NULL; long size1, size2; FILE *filedes; /* * Assume size1 and size2 are appropriately initialized * */ filedes = fopen("out.txt", "w+"); if (filedes < 0) { /* Handle error */ } buffer = (char *)calloc(1, size1); if (buffer == NULL) { /* Handle error */ } fwrite(buffer, sizeof(char), size2, filedes); free(buffer); buffer = NULL; fclose(filedes); |
...
This compliant solution ensures that the correct number of characters are written to the file.
| Code Block | ||
|---|---|---|
| ||
char *buffer = NULL; long size1, size2; FILE *filedes; /* * Assume size1 and size2 are appropriately initialized */ filedes = fopen("out.txt", "w+"); if (filedes < 0){ /* Handle error */ } buffer = (char *)calloc(1, size1); if (buffer == NULL) { /* Handle error */ } /* * Accept characters in to the buffer * Check for buffer overflow */ size2 = strlen(buffer) + 1; fwrite(buffer, sizeof(char), size2, filedes); free(buffer); buffer = NULL; fclose(filedes); |
Risk Assessment
Failure to follow the recommendation could result in a non-null-terminated string being written to a file. This will create problems when the program tries to read it back as a c-string.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
FIO18-CPP | Medium | Probable | Medium | P12 | L1 |
Other Languages
This rule can be found in the C++ Secure Coding Practice as FIO18-CPP. Never expect write() to terminate the writing process at a null character.
...
| Wiki Markup |
|---|
\[1\] [http://www.opengroup.org/onlinepubs/009695399/functions/fwrite.html]
\[2\] \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] |