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
an extension, in C11 it's undefined behavior.
Regtested/bootstrapped on x86_64, ok for trunk?
2014-01-13 Marek Polacek <[email protected]>
PR c/58346
c/
* c-typeck.c (pointer_to_empty_aggr_p): New function.
(pointer_diff): Give an error on arithmetic on pointer to an
empty aggregate.
testsuite/
* gcc.dg/pr58346.c: New test.
--- gcc/c/c-typeck.c.mp 2014-01-13 15:47:01.316105676 +0100
+++ gcc/c/c-typeck.c 2014-01-13 16:03:35.513081392 +0100
@@ -3427,6 +3427,18 @@ parser_build_binary_op (location_t locat
return result;
}
+
+/* Return true if T is a pointer to an empty struct/union. */
+
+static bool
+pointer_to_empty_aggr_p (tree t)
+{
+ t = strip_pointer_operator (t);
+ if (!RECORD_OR_UNION_TYPE_P (t))
+ return false;
+ return TYPE_FIELDS (t) == NULL_TREE;
+}
+
/* Return a tree for the difference of pointers OP0 and OP1.
The resulting tree has type int. */
@@ -3536,6 +3548,9 @@ pointer_diff (location_t loc, tree op0,
/* This generates an error if op0 is pointer to incomplete type. */
op1 = c_size_in_bytes (target_type);
+ if (pointer_to_empty_aggr_p (TREE_TYPE (orig_op1)))
+ error_at (loc, "arithmetic on pointer to an empty aggregate");
+
/* Divide by the size, in easiest possible way. */
result = fold_build2_loc (loc, EXACT_DIV_EXPR, inttype,
op0, convert (inttype, op1));
--- gcc/testsuite/gcc.dg/pr58346.c.mp 2014-01-13 15:48:20.011420141 +0100
+++ gcc/testsuite/gcc.dg/pr58346.c 2014-01-13 16:01:41.741713601 +0100
@@ -0,0 +1,21 @@
+/* PR c/58346 */
+/* { dg-do compile } */
+/* { dg-options "-std=gnu99" } */
+
+struct U {};
+static struct U b[6];
+static struct U **s1, **s2;
+
+int
+foo (struct U *p, struct U *q)
+{
+ return q - p; /* { dg-error "arithmetic on pointer to an empty aggregate" }
*/
+}
+
+void
+bar (void)
+{
+ __PTRDIFF_TYPE__ d = s1 - s2; /* { dg-error "arithmetic on pointer to an
empty aggregate" } */
+ __asm volatile ("" : "+g" (d));
+ foo (&b[0], &b[4]);
+}
Marek