[m]allocation question

Chris Torek chris at mimsy.umd.edu
Sun Sep 30 03:11:23 AEST 1990


In article <871 at usage.csd.unsw.oz.au> cameron at usage.csd.oz
(Cameron Simpson,Uhmmm..???? Who knows) writes:
>I have been using the macro
>    #define		fsizeof(type,field) sizeof(((type *)NULL)->field)
>... Could someone ... re-iterate the explaination of why this macro
>can break, while sizeof(*t) is fine.

It is fairly simple:

	sizeof expression

and

	sizeof(type)

are both required to produce a compile-time constant, and to not evaluate
the expression at runtime (to boldly split an infinitive in the cause of
precision :-) ).  There is one constraint on *you*, however: all of the
`expression' or the `type' must be meaningful.

This gets a bit dodgy when it comes to expressions like

	((type *)NULL)->field

This consists of three sub-expressions, namely:

	NULL	(either 0 or (void *)0)
	cast	(to `type *')
	p->f	(select `field')

The NULL is certainly well-defined, as is the cast on it.  The question
comes down to `is nil->field well-defined?'.  The opinion seems to be that
it is not.  Most compilers are perfectly happy with it, but the ANSI
standard appears to allow them to be wroth.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.std.c mailing list