Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated with latest C description.

Standard FILE objects and their underlying representation (file descriptors on POSIX ® platforms or handles elsewhere) are a finite resource that must be carefully managed. The maximum number of files that an implementation guarantees may be open simultaneously is bounded by the FOPEN_MAX macro defined in <stdio.h>. The value of the macro is guaranteed to be at least 8. Thus, portable programs must either avoid keeping more than FOPEN_MAX files at the same time or be prepared for functions such as fopen() to fail due to resource exhaustion.

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. In addition, keeping files open longer than necessary increases the risk that data written into in-memory file buffers will not be flushed in the event of abnormal program termination, for example as a result of an uncaught exception (see also ERR30-CPP. Try to recover gracefully from unexpected errors). To prevent file descriptor leaks and to guarantee that any buffered data will be flushed into permanent storage, files should must be closed when they are no longer needed.

Be careful not to Since the behavior of a program is undefined when it uses the value of a pointer to a FILE object after the associated file is closed (see undefined behavior 140 in Annex J.2 of C99), programs that close the standard streams (especially stdout): doing so will send an EOF to any application on the other side of a pipe, possibly causing it to take actions that shouldn't have occurred until the first application terminates but also stderr and stdin) must be careful not to use the stream objects in subsequent function calls, especially those that implicitly operate on such objects (such as printf(), perror(), and getc()).

Noncompliant Code Example

...