...
Noncompliant Code Example
In the following piece of codethis noncompliant code example, the size of the buffer is stored in size1, but size2 number of characters are written in to the file. If size2 is greater than size1, write() will not stop copying characters at the null character.
| Code Block | ||
|---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> int main(){ char *buffer = NULL; long size1, size2; FILE *filedes; /* ... * Assume size1 and size2 are appropriately initialized * ... */ filedes = fopen("out.txt", "w+"); if (filedes < 0) { /* Handle return 0;error */ } buffer = (char *)calloc(1, size1); if (!buffer == NULL) { /* Handle return 0;error */ } fwrite(buffer, sizeof(char), size2, filedes); free(buffer); buffer = NULL; fclose(filedes); return 0; } |
Compliant Code Example
The following code will ensure This compliant solution ensures that the right correct number of characters are written in to the file.
| Code Block | ||
|---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> int main(){ char *buffer = NULL; long size1, size2; FILE *filedes; /* ... * Assume size1 and size2 are appropriately initialized * ... */ filedes = fopen("out.txt", "w+"); if (filedes < 0){ /* Handle return 0;error */ } buffer = (char *)calloc(1, size1); if (!buffer == NULL) { /* Handle return 0;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); return 0; } |
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.
...