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

            Bug ID: 92937
           Summary: missing warning on a store with index >= malloc size
           Product: gcc
           Version: 10.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: msebor at gcc dot gnu.org
  Target Milestone: ---

The -Wstringop-overflow logic for determining out of bounds stores into
variably sized objects (alloca, malloc, and VLAs) at offsets that are equal to
or greater than the size considers the ranges of the size and the offset
independently of one another.  When both the size is a range and the offset is
equal or greater than the size, the logic doesn't accurately reflect their
relationship: it uses the upper bound of the size but the lower bound of the
index.  This is necessary when the two are unrelated but gets in the way of
diagnosing bugs when they're the same or one is a function of the other like in
the test cases below.  In f(), it causes the warning to be issued only in the
last case.  In g(), because the upper bound of the size is INT_MAX (if n is
positive), no warning is issued even for the obviously excessive index.

$ cat b.c && gcc -O2 -S -Wall -ftrack-macro-expansion=0 b.c
void sink (void*);

void* f (int n)
{
  if (n < 3 || 5 < n) n = 3;

  char *p = __builtin_malloc (n);

  p[n] = 0;       // missing warning
  p[n + 1] = 0;   // missing warning
  p[n + 2] = 0;   // warning here

  return p;
}

void* g (int n)
{ 
  char *p = __builtin_malloc (n);

  p[n] = 0;          // missing warning
  p[n + 1] = 0;      // missing warning
  p[n + 9999] = 0;   // missing warning

  return p;
}
b.c: In function ‘f’:
b.c:11:12: warning: writing 1 byte into a region of size 0
[-Wstringop-overflow=]
   11 |   p[n + 2] = 0;   // warning here
      |   ~~~~~~~~~^~~

Reply via email to