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

            Bug ID: 109577
           Summary: -Wanalyzer-allocation-size mishandles
                    __builtin_mul_overflow
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: analyzer
          Assignee: dmalcolm at gcc dot gnu.org
          Reporter: eggert at gnu dot org
  Target Milestone: ---

This is (GCC) 13.0.1 20230401 (Red Hat 13.0.1-0) on x86-64.

Compile the following program with 'gcc -O2 -S -fanalyzer t.c'. GCC will
incorrectly complain "warning: allocated buffer size is not a multiple of the
pointee's size [CWE-131]". But the allocated buffer size must be a multiple of
sizeof (double), due to the checked call to __builtin_mul_overflow. As the
code's comment suggests, if the code uses plain * (integer multiply) instead
the bogus warning goes away.

I ran into this problem when compiling Emacs, which is often careful about
checking integer overflow. As a result I think I'll compile Emacs with
-Wno-analyzer-allocation-size to suppress false alarms, which would be a real
shame since this warning is useful for lower-quality code.

  #include <stdlib.h>

  int
  main (int argc, char **argv)
  {
    size_t s;
    double *d;
    if (__builtin_mul_overflow (argc, sizeof *d, &s))
      return 1;
    // No warning if the above is replaced with 's = argc * sizeof *d;'.
    d = malloc (s);
    if (d && s)
      {
        d[0] = argc;
        d[argc - 1] = argc + 1;
        return d[0];
      }
    return 0;
  }

Reply via email to