[C PATCH] Disallow subtracting pointers to empty structs (PR c/58346)

Florian Weimer fweimer@redhat.com
Mon Jan 13 17:21:00 GMT 2014

On 01/13/2014 05:32 PM, Marek Polacek wrote:

> This doesn't really fix the PR, but solves a related issue, where we
> have e.g.
> struct U {};
> static struct U b[6];
> int foo (struct U *p, struct U *q)
> {
>    return q - p;
> }
> int main()
> {
>    return foo (&b[0], &b[4]);
> }

> Such a program SIGFPEs at runtime.  But subtraction of pointers to empty
> structures/unions doesn't really make sense and this patch forbids that.
> Note that GCC permits a structure/union to have no members, but it's only

> +  if (pointer_to_empty_aggr_p (TREE_TYPE (orig_op1)))
> +    error_at (loc, "arithmetic on pointer to an empty aggregate");

You need to check the size of the aggregate, not if it has no members. 
With your patch applied, if the struct definition in your test case is 
changed to this:

struct U { char empty[0]; };

it still compiles and fails at run time.

Empty structs have size 1 in C++, but structs with a zero-length array 
have size 0, so the C++ compiler should be changed as well.

Florian Weimer / Red Hat Product Security Team

More information about the Gcc-patches mailing list