[clang] [clang][analyzer] Improved PointerSubChecker (PR #93676)

DonĂ¡t Nagy via cfe-commits cfe-commits at lists.llvm.org
Mon Jun 3 03:38:58 PDT 2024


NagyDonat wrote:

> With the current version I have the following observations:
> 
>     * There is a warning for `(&x + 1) - &x` and `(&x - 1) - &x`. Should this be fixed?

The expression `(&x + 1) - &x` is valid and should not produce a warning. It could appear e.g. in code that's structured like
```
void log_observations(double *begin, double *end, /*...*/) {
  log_observation_count(end - begin);
  // also log the actual observations
}
void do_observations(/*...*/) {
  double array[1024], *p = array;
  //...
  while (can_observe()) {
    *p++ = /* ... */
  }
  log_observations(array, p);
}
void do_single_observation(/*...*/) {
  if (!can_observe())
    return;
  double result = /* ... */
  // ...
  log_observations(&result, &result + 1);
}
```

On the other hand `(&x - 1) - &x` is not standard-compliant, because the standard guarantees an "after-the-end" pointer (which is valid in calculations but must not be dereferenced) but it doesn't accept a "before-the-begin" pointer.

>     * The code `(int *)((char *)(&a[4]) + sizeof(int)) - &a[4]` produces no warning but `(int *)((char *)(&a[4]) + 1) - &a[4]` produces warning.

That's very nice, even a slightly less accurate solution would be acceptable.

> For 2-dimensional arrays there is warning for all of these cases (lines 44-47 in the test file). Is this possible to fix (to get warning in all cases), or no warning is needed here?

I'd say that the current behavior (warning on all of 44-47) is OK here -- this is very unusual trickery and deserves a highlight. However I could also accept a situation where there was no warning for these complex multidimensional cases.

https://github.com/llvm/llvm-project/pull/93676


More information about the cfe-commits mailing list