Semmle 1.20
Skip to end of metadata
Go to start of metadata

Name: Open file is not closed

Description: A function always returns before closing a file that was opened in the function. Closing resources in the same function that opened them ties the lifetime of the resource to that of the function call, making it easier to avoid and detect resource leaks.

ID: cpp/file-never-closed

Kind: problem

Severity: warning

Query: FileNeverClosed.ql
/**
 * @name Open file is not closed
 * @description A function always returns before closing a file that was opened in the function. Closing resources in the same function that opened them ties the lifetime of the resource to that of the function call, making it easier to avoid and detect resource leaks.
 * @kind problem
 * @id cpp/file-never-closed
 * @problem.severity warning
 * @tags efficiency
 *       security
 *       external/cwe/cwe-775
 */
import FileClosed

from Expr alloc
where fopenCall(alloc) and not fopenCallMayBeClosed(alloc)
select alloc, "The file is never closed"

This rule finds calls to fopen with no corresponding fclose call in the entire program. Leaving files open will cause a resource leak that will persist even after the program terminates.

This check is an approximation, so some results may not be actual defects in the program. It is not possible in general to compute the exact value of the variable without running the program with all possible input data.

Recommendation

Ensure that all file or socket descriptors allocated by the program are freed before it terminates.

Example

int main(int argc, char* argv[]) {
	FILE *fp = fopen("foo.txt", "w");
	int status = 0;
	... //code that does not close fp
	return status; //fp is never closed
}