...
In this 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>
char *buffer = NULL;
size_t size1, size2;
FILE *filedes;
/*
* Assume size1 and size2 are appropriately initialized
*/
filedes = fopen("out.txt", "w+");
if (filedes == NULL) {
/* Handle error */
}
buffer = (char *)calloc( 1, size1);
if (buffer == NULL) {
/* Handle error */
}
fwrite(buffer, 1, 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;
size_t size1, size2;
FILE *filedes;
/*
* Assume size1 is appropriately initialized
*/
filedes = fopen("out.txt", "w+");
if (filedes == NULL){
/* 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, 1, size2, filedes);
free(buffer);
buffer = NULL;
fclose(filedes);
|
...