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 to the end of a file. However, if fwrite() fails, then write_data() returns -1 in error without properly closing the stream to DataFile.txt.
| 
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;
}
 | 
To correct this example, the code is modified to ensure DataFile.txt is always closed.
| 
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;
}
 | 
Failing to properly close files may allow unintended access to system resources, or exhaust system resources.
| \[[Dowd 06|AA. C References#Dowd 06]\] Chapter 10, "UNIX Processes" (File Descriptor Leaks 582-587) \[[CWE 403|http://cwe.mitre.org/data/definitions/403.html]\] UNIX File Descriptor Leaks |