Failing to close files when they are no longer needed may allow attackers to exhaust, and possibly manipulate, system resources. This phenomenon is typically referred to as file descriptor leakage, although file pointers may also be used as an attack vector. To prevent file descriptor leaks, file pointers and file descriptors should be closed when they are no longer needed.
...
In this non-compliant example, an array of characters is written appended to the end of a file. However, if the call to fwrite() fails, then write_data() returns -1 in error without properly closing fails to close the open file DataFile.txt.
| Code Block | ||
|---|---|---|
| ||
int write_data(char *data, size_t data_size) {
FILE * fptr;
size_t written;
fptr = fopen("DataFile.txt", "a");
if (fptr == NULL) {
/* Handle fopen() error */
}
written = fwrite(data, sizeof(char), data_size, fptr);
if (written < data_size) {
return -1;
}
fclose(fptr);
return 0;
}
|
Compliant Solution
To correct In this examplecompliant solution, the code is modified to ensure that the DataFile.txt file is always closed.
| Code Block | ||
|---|---|---|
| ||
int write_data(char *data, size_t data_size) {
FILE * fptr;
size_t written;
int result = 0;
fptr = fopen("DataFile.txt", "a");
if (fptr == NULL) {
/* Handle fopen() error */
}
written = fwrite(data, sizeof(char), data_size, fptr);
if (written < data_size) {
result = -1;
}
fclose(fptr);
return result;
}
|
...