sizeof a struc field

Rahul Dhesi dhesi at sunseeker.UUCP
Thu Oct 26 14:44:30 AEST 1989


In article <11372 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn) writes:
>My argument is that the Standard deliberately does not
>assign a meaning for
>	((type *)0)->member
>This is a consequence of the semantics: "A postfix expression followed
>by an arrow -> and an identifier designates a member of a structure or
>union object".  But there is no object in this case (a null pointer
>does not point to an object).

I find this argument persuasive.

However, the argument is persuasive only because the constant 0 has a
special meaning in C.  We know a null pointer does not point to an
object.  But what happens if we do the following?

        sizeof ((type *)1)->member

There might or might not be an object in this case.  It depends on the
implementation.  The C standard cannot guarantee that (type *)1 points
to a valid object.  It also cannot guarantee that it doesn't.  A
warning is probably in order, but it would be wrong for the C compiler
to consider this an error *purely because of what the standard says*.

If the compiler is smart enough to recognize that (type *)1
does not in fact point to a valid object, *then* it should complain.
(But, unless you want to prevent people from writing device drivers, it
had better still only give a warning, not a fatal compilation error.)

It also occurs to me that

        sizeof ((type *)x)->member

would be an interesting case to analyze, where x is some variable.  At
compile time x does not yet have a value, so we cannot guarantee that
(type *)x points to any real object.  What does the standard say about
this?  "gcc -ansi -pedantic" didn't seem to mind this:


     main()
     {
	 int x;
	 struct y { int a; int b; };
	 printf("size=%d\n", sizeof ((struct y *)x)->a);
     }


I have lost track of how this controversy began, so I hope I haven't
gone off at a tangent.

Rahul Dhesi <dhesi%cirrusl at oliveb.ATC.olivetti.com>
UUCP:  oliveb!cirrusl!dhesi
Use above addresses--email sent here via Sun.com will probably bounce.



More information about the Comp.lang.c mailing list