https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100540
Bug ID: 100540
Summary: -Wanalyzer-file-leak false positive due to
conditionals
Product: gcc
Version: 11.1.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: analyzer
Assignee: dmalcolm at gcc dot gnu.org
Reporter: andrew at ishiboo dot com
Target Milestone: ---
Test program:
#include <stdio.h>
#include <string.h>
char foo(const char *filename) {
FILE *fp;
if (!filename || strcmp(filename, "-") == 0) {
fp = stdin;
} else {
fp = fopen(filename, "r");
}
char c = fgetc(fp);
if (fp != stdin) {
fclose(fp);
}
return c;
}
int main(int argc, char **argv) {
if (argc > 1) {
char c = foo(argv[1]);
printf("%c\n", c);
}
return 0;
}
False positive:
$ gcc-11 -fanalyzer -c /tmp/test.c
/tmp/test.c: In function 'foo':
/tmp/test.c:18:12: warning: leak of FILE 'fp' [CWE-775] [-Wanalyzer-file-leak]
18 | return c;
| ^
'foo': events 1-6
|
| 6 | if (!filename || strcmp(filename, "-") == 0) {
| | ^
| | |
| | (1) following 'false' branch...
|......
| 9 | fp = fopen(filename, "r");
| | ~~~~~~~~~~~~~~~~~~~~
| | |
| | (2) ...to here
| | (3) opened here
|......
| 14 | if (fp != stdin) {
| | ~
| | |
| | (4) following 'false' branch...
|......
| 18 | return c;
| | ~
| | |
| | (5) ...to here
| | (6) 'fp' leaks here; was opened at (3)
|
Expected outcome:
The analyzer should understand that without anything modifying stdin, stdout,
stderr, the return of fopen() can not be stdin, stdout, or stderr, so
fclose(fp) must be hit.