offsets in structures.

Henry Spencer henry at utzoo.UUCP
Tue Oct 23 05:58:55 AEST 1984


> Although I see no particular use for the following piece of code,
> I believe that it is supposed to be legal both now and in the ANSI
> standard:
> 
> 	char	*foo;
> 
> 	foo -= (long)foo;	/* or (int) perhaps */
> 	/* foo now is NULL */

This falls down if pointers are not byte indexes, e.g. if the byte info
is up in some of the high-order bits.  (I think the pdp10 does that.)
Remember that the ptr--->long conversion is not required to produce a
sensible number.  There is also a more subtle assumption here, that memory
is in fact organized as an array of bytes, so subtracting the "position"
of a byte pointer from the pointer gives 0.  (I can't immediately think
of a counterexample, but it's not ruled out.)  Finally, nowhere does the
ANSI standard (or K&R) say that *any* computed pointer value, regardless
of the computation, must compare equal to integer constant 0 (i.e. NULL).
The only way to get a pointer that is guaranteed to compare equal to NULL
is to derive it from an explicit NULL.

> 	char	*malloc(), *where;
> 
> 	where = malloc( (unsigned)40 );
> 
> 	subr( where );	/* check validity of `where' and does something */
> 
> Here a NULL pointer must be type-compatible with other pointers.  Using
> a special "nil" pointer could easily get in the way here (subr() might
> end up with special-case "nil"-handling in-line code every time its
> parameter is used).

Why?  If subr() compares the pointer to an explicit NULL, then that
comparison is done against the special "nil" value.  If the comparison
is against a pointer derived from an explicit NULL, same thing.  If the
comparison is against anything else, there are no promises made by the
ANSI draft or K&R.  The choice of bit pattern to represent NULL is
entirely irrelevant.

> What more does using special "nil" get you than using a 0, apart from
> hardware check against dereferencing NULL?  In any case, the hardware
> check is unnecessary if you write your code correctly.  Are we all
> hackers or are there some professional programmers out there?

Among other things, on some "smart" pieces of hardware, you cannot even
load some bit patterns into a "pointer" register without getting a trap.
On such hardware, you can't use such a bit pattern to represent NULL
without all kinds of hassles when manipulating might-be-NULL pointers.
On at least one such machine that I've heard of, all-zeros is one of the
bad bit patterns.
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,linus,decvax}!utzoo!henry



More information about the Comp.lang.c mailing list