https://gcc.gnu.org/bugzilla/show_bug.cgi?id=127581

            Bug ID: 127581
           Summary: -Wanalyzer-fd-leak false positive for dup2
           Product: gcc
           Version: 16.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: analyzer
          Assignee: dmalcolm at gcc dot gnu.org
          Reporter: norbert.eicker at gmx dot de
  Target Milestone: ---

Created attachment 65673
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=65673&action=edit
Simple reproducer

When compiling the reproducer I get:
> gcc-16 -fanalyzer -c reproducer.c
reproducer.c: In function ‘redirect’:
reproducer.c:9:8: warning: leak of file descriptor ‘dup2(fd, 1)’ [CWE-775]
[-Wanalyzer-fd-leak]
    9 |     if (dup2(fd, STDOUT_FILENO) == -1) return -1;
      |        ^
  ‘redirect’: events 1-3
    7 |     if (fd < 0) return -1;
      |        ^
      |        |
      |        (1) following ‘false’ branch (when ‘fd >= 0’)... ─>─┐
      |                                                            │
      |                                                            │
      |┌───────────────────────────────────────────────────────────┘
    8 |│
    9 |│    if (dup2(fd, STDOUT_FILENO) == -1) return -1;
      |│        ~~~~~~~~~~~~~~~~~~~~~~~
      |│        |
      |└───────>(2) ...to here
      |         (3) opened here
  ‘redirect’: event 4
    9 |     if (dup2(fd, STDOUT_FILENO) == -1) return -1;
      |        ^
      |        |
      |        (4) ⚠  ‘dup2(fd, 1)’ leaks here; was opened at (3)

I guess this is a false positive for various reasons:
- the new file descriptor is not only returned by dup2() but also forced to be
the second argument -- unless -1 is returned to indicate a failure
- if the second argument is in the range [0,2] (i.e. one of STDIN_FILENO,
STDOUT_FILENO, STDERR_FILENO) the new file descriptor shall not assumed to be
leaked

If the second argument has a value different from [0,2], it shall from now on
take the role of a file descriptor. I.e. at the end of the scope of the second
argument a leak of a file descriptor shall be indicated unless it was close()ed
before
  • [Bug analyzer/127581] New: -Wana... norbert.eicker at gmx dot de via Gcc-bugs

Reply via email to