This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [PATCH]: Fix PR tree-optimization/21407


Daniel Berlin wrote:

IE it's not legal in C to do something like this:

struct foobase
{
	int b;
};
struct foo
{
	int a;
	struct foobase b;
};

void func (struct foobase *a)
{
	struct foo *b = (struct foo *)(((char *)a) - (offsetof (foo, b) -
offsetof (foo, a);

	/* Yay, i've got a struct foo * back! */
	if (b->a ! 5)
		abort();
}
>
int main(void)
{
	struct foo a;
	a.a = 5;
	func(&a.b);
	return 0;
}

Why is that not legal? The only reason I can imagine is that you've done pointer arithmetic that goes beyond a single array, but if there's no exemption for character pointers in that case, there should be, at least in GNU C, where we assume unsegmented memory.


Do you think it's legal if the fields are in the other order:

  struct foo {
    struct foobase b;
    int a;
  }

  void func (struct foobase *a) {
    struct foo *b = (struct foo *) a;
    if (b->a != 5) abort ();
  }

That's a common way of doing object orientation in C (with "if (a->kind == FOO)", guarding the base-to-derived cast). I certainly think it's valid.

--
Mark Mitchell
CodeSourcery, LLC
mark@codesourcery.com
(916) 791-8304


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]