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

--- Comment #3 from James Abbatiello <abbeyj+gcc at gmail dot com> ---
If "there is no way for GCC to know that p[i] would access out of bounds" then
it shouldn't warn about this, should it?  It should only warn in cases where it
can prove that the access is out of bounds.  That's why `char arr[10]; arr[10]
= 0;` warns but `char arr[10]; arr[x] = 0;` does not.  The first is always
incorrect.  The second may index out of bounds but the compiler can't prove
that and, to avoid false-positives, it has to assume that `x` will be in bounds
at runtime.

If you'd like a complete program, how about this:

```
struct my_descriptor {
  int length;
  char *pointer;
};

extern "C" int puts(const char *);

void print(const my_descriptor *desc)
{
  char output[9];
  char *p = output;
  for (int i = desc->length; i >= 0; i--) {
    p[i] = desc->pointer[i];
  }
  puts(output);
}

int main() {
  char in[] = "abcd";
  my_descriptor desc = { 4, in };
  print(&desc);
  return 0;
}
```

This should print "abcd" and contains no out of bounds writes, as far as I can
tell.  GCC still produces the warning.

Reply via email to