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

            Bug ID: 125622
           Summary: [14/15 Regression] False positive
                    Wanalyzer-deref-before-check fanalyzer warnings for
                    e.g. strchr()
           Product: gcc
           Version: 15.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: analyzer
          Assignee: dmalcolm at gcc dot gnu.org
          Reporter: zany at triq dot net
  Target Milestone: ---

With gcc 15 for this function (minimal reproducible example, not sensible
as-is) with relevant #include <string.h> expanded for brevity:

char * strchr(const char *__s, int __c); // #include <string.h>

void bogus(char *p)
{
    if (*p) {
        strchr(p, '!');
    }
}


$ gcc-15 -fsanitize=undefined -fanalyzer -c test.c


We get a false positive -Wanalyzer-deref-before-check warning:

test.c: In function ‘bogus’:
test.c:7:9: warning: check of ‘p’ for NULL after already dereferencing it
[-Wanalyzer-deref-before-check]
    7 |         strchr(p, '!');
      |         ^~~~~~~~~~~~~~
  ‘bogus’: event 1
    6 |     if (*p) {
      |         ^~
      |         |
      |         (1) pointer ‘p’ is dereferenced here
  ‘bogus’: events 2-4
    6 |     if (*p) {
      |        ^
      |        |
      |        (2) following ‘true’ branch... ─>─┐
      |                                          │
      |                                          │
      |┌─────────────────────────────────────────┘
    7 |│        strchr(p, '!');
      |│        ~~~~~~~~~~~~~~
      |│        |
      |└───────>(3) ...to here
      |         (4) ⚠️   pointer ‘p’ is checked for NULL here but it was already
dereferenced at (1)


I don't see where the code is wrong to do some checks on p, then conditionally
run strchr().

A bit more sensible code example which produces the same false positive warning
might be:

char *foo(char *p)
{
    if (*p == '?') {
        return strchr(p, '!');
    }
    return 0;
}

Reply via email to