This principle underscores the detection of occurrences within code where resources, such as file descriptors, aren't adequately released
or closed
, especially prevalent in C programming. These situations arise when files remain unclosed after being opened or when other system resources aren't appropriately handled. To prevent potential problems, it's crucial to prioritize proper resource management and cleanup throughout the codebase.
1#include <stdio.h>
2#include <stdlib.h>
3
4FILE *incompleteCleanupNonCompliant() {
5 FILE *f;
6 f = fopen("example.txt", "r");
7 if (f == NULL) {
8 perror("Failed to open file");
9 }
10 // Noncompliant: File not closed
11 return f;
12}
1#include <stdio.h>
2#include <stdlib.h>
3
4FILE *incompleteCleanupCompliant() {
5 FILE *f = fopen("example.txt", "r");
6 if (f == NULL) {
7 perror("Failed to open file");
8 }
9 // Compliant: File closed before returning
10 fclose(f);
11 return f;
12}