Creating pointer with all bits 0 (was: Referencing NULL pointers)

Mark Brader msb at sq.sq.com
Thu Aug 31 15:27:56 AEST 1989


> > could you not access memory location 0 by writing:
> >	p = 0;  /* integer variable that happens to be set to zero */
> >	data = *(int *)p;  /* no constant expression in this line */

> Probably, but there's nothing to stop a cast doing something strange.
> This may work better (but of course is still completely unreliable):
>    union {int i; int *p} x;
>    x.i = 0;
>    data = *x.p;

Int indeed.  However, this is suggestive.  You could do:

   union {char c [sizeof (int *)]; int *p;} x;
   int i;
   for (i = 0; i < sizeof x.c; ++i) x.c[i] = 0;
   data = *x.p;

On the other hand, it's simpler to use memset():

      int *p;
      memset ((void *) p, 0, sizeof p);
      data = *p;

Or bzero() if you have that and not memset(), or for that matter
there's the trickier but more universally available way:

      strncpy ((char *) p, "", sizeof p);

It may as well be repeated for anyone who's coming in late that
the point here is to get a pointer p with all bits zero, for use
on a machine where null pointers have some other pattern of
bits and all-bits-zero is a meaningful pointer.  It may as well
also be repeated that the bit pattern (or patterns; they could
depend on the type) of null pointers have nothing to do with the
fact that 0 is a correct way to write a null pointer constant.

-- 
Mark Brader, SoftQuad Inc., Toronto, utzoo!sq!msb, msb at sq.com
#define	MSB(type)	(~(((unsigned type)-1)>>1))

This article is in the public domain.



More information about the Comp.lang.c mailing list