[cfe-commits] PATCH: Enhance array bounds checking

Kaelyn Uhrain rikka at google.com
Thu Jul 14 11:13:17 PDT 2011


On Thu, Jul 14, 2011 at 10:28 AM, Ted Kremenek <kremenek at apple.com> wrote:

> Hi Kaelyn,
>
> I was reviewing this patch (which I think is a great step), and I had a
> high-level comment about the following test case:
>
> +void swallow (const char *x) { (void)x; }
> +void test_pointer_arithmetic() {
> +  const char hello[] = "Hello world!"; // expected-note 2 {{declared
> here}}
> +  const char *helloptr = hello;
> +
> +  swallow("Hello world!" + 6); // no-warning
> +  swallow("Hello world!" - 6); // expected-warning {{refers before the
> beginning of the array}}
> +  swallow("Hello world!" + 14); // expected-warning {{refers past the end
> of the array}}
>
> Do we really want this to be a warning?  There are plenty of examples where
> an out-of-bounds pointer is computed for legit reasons.  As long as that
> address is not dereferenced, there isn't necessarily a problem.  I'm fearful
> this may generate a fair amount of noise on codebases that do elaborate
> tricks with pointer offsets.  Indeed this very example doesn't actually
> exhibit a "bug".
>

This patch came about from a Google-internal bug requesting a warning for
pointer arithmetic with string constants that is guaranteed to be undefined.
Given that the warning only triggers on pointer arithmetic involving a
constant-sized array and a constant value (as that's the only time the
compiler is guaranteed to know the result is invalid in regard to the array
itself) if and only if the result goes more than one past the end of the
array, I doubt there are many elaborate pointer offset tricks that would
trigger this warning and are not inherently buggy. The resulting pointers
would refer to arbitrary memory in or near the static program code/data or
the stack since the arrays that could trigger this warning are pretty much
by definition not allocated on the heap. Also, math on pointers (not arrays
or constant strings) does not trigger the warning, as shown by the uses of
helloptr in the test case--and at least in my limited experience, all of the
fancy pointer arithmetic tricks I've seen have on pointers (possibly to
constant arrays), not on literal arrays or array variables. Given the
constraints on when the warning will be triggered for pointer arithmetic, I
feel it does much more good than harm.

Cheers,
Kaelyn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20110714/f56f3964/attachment.html>


More information about the cfe-commits mailing list