[Bug middle-end/113540] missing -Warray-bounds warning with malloc and a simple loop

2024-01-23 Thread vincent-gcc at vinc17 dot net via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113540

--- Comment #2 from Vincent Lefèvre  ---
Thanks for the explanations, but why in the following case

void foo (void)
{
  volatile char t[4];
  for (int i = 0; i <= 4; i++)
t[i] = 0;
  return;
}

does one get the warning (contrary to the use of malloc)?

[Bug middle-end/113540] missing -Warray-bounds warning with malloc and a simple loop

2024-01-22 Thread rguenth at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113540

Richard Biener  changed:

   What|Removed |Added

 Blocks||56456
   Keywords||diagnostic
 Status|UNCONFIRMED |NEW
 Ever confirmed|0   |1
   Last reconfirmed||2024-01-23

--- Comment #1 from Richard Biener  ---
If you remove the volatile, like

#include 

char *foo (void)
{
  char *t;
  t = malloc (4);
  for (int i = 0; i <= 4; i++)
t[i] = 0;
  return t;
}

you get

t.c: In function 'foo':
t.c:8:10: warning: '__builtin_memset' writing 5 bytes into a region of size 4
[-Wstringop-overflow=]
8 | t[i] = 0;
  | ~^~~
t.c:6:7: note: destination object of size 4 allocated by 'malloc'
6 |   t = malloc (4);
  |   ^~

note this is because we then unroll the loop.  If you change it like

#include 

short *foo (void)
{
  short *t;
  t = malloc (8);
  for (int i = 0; i <= 4; i++)
t[i] = 13;
  return t;
}

you get

t.c: In function 'foo':
t.c:8:6: warning: array subscript 4 is outside array bounds of 'short int[4]'
[-Warray-bounds=]
8 | t[i] = 13;
  | ~^~~
t.c:6:7: note: at offset 8 into object of size 8 allocated by 'malloc'
6 |   t = malloc (8);
  |   ^~

because we unroll the loop.  Upping the bounds like

#include 

short *foo (void)
{
  short *t;
  t = malloc (64);
  for (int i = 0; i <= 32; i++)
t[i] = 13;
  return t;
}

no longer warns because we hit unroll limits.  This is also the reason
we do not diagnose the original testcase - there's currently no analysis
done to compute the set of values 'i' must reach for the purpose of
array-bound diagnostics.  Instead we use value-ranges which are
conservative, aka [-INF, INF] is "correct".  But that means we only
diagnose cases where _all_ values of the range fall outside of the
array.

Using niter analysis and SCEV we could do a better job in cases like the
one in this bug.

I'm quite sure we have related/duplicate bugreports for this already.


Referenced Bugs:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56456
[Bug 56456] [meta-bug] bogus/missing -Warray-bounds