On Sun, 6 Sep 2020 16:48:18 -0700 Charles Mills wrote:

> I'm familiar with the use of NULL as a "special" value. I think
> the C standard says that 0 may never be a valid address.

The ISO/IEC 9899:20xx "C" standard cites no restriction on the
value zero being an invalid address.

An extraction from the standard:

  Topic 6.3.2.3 Pointers

  An integer may be converted to any pointer type.  Except as
  previously specified, the result is implementation-defined, might
  not be correctly aligned, might not point to an entity of the
  referenced type, and might be a trap representation.

  An integer constant expression with the value 0, or such an
  expression cast to type void *, is called a null pointer
  constant.  If a null pointer constant is converted to a pointer
  type, the resulting pointer, called a null pointer, is guaranteed
  to compare unequal to a pointer to any object or function.

In other words, the standard requires that the simple assignment of
the integer value zero to a pointer causes that pointer to be
assigned the implementation defined value of NULL.  For example:

  char *somepointer = 0;

A conforming compiler treats the above assignment as:

  char *somepointer = NULL;

While on most implementations this assigns the value zero to
"somepointer", it is not necessarily so; the value of NULL may be
any bit pattern which satisfies the constraints stated in the
standard.

Most implementations define NULL (for example, in stdlib.h or
stddef.h) as:

#define NULL    ((void *)0)

An example of an implementation dependent way to get the value zero
assigned to a pointer is shown below.  The "trick" here is that the
value being assigned is not a constant expression.

  volatile int intzero = 0;
  char *somepointer = (char *)intzero;

C does not prohibit dereferencing the NULL pointer; rather it makes
it undefined (and implementation dependent) behavior.  Certainly, on
an IBM mainframe beginning with the S/360 and continuing to the
present, it would be awkward (and obnoxious) to be unable to
reference the PSA via a pointer variable.

Bob

Reply via email to