tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: NULL pointer arithmetic issues

On Mon, Feb 24, 2020 at 05:35:22PM -0500, Mouse wrote:
> > Unless I remember wrong, older C standards explicitly say that the
> > integer 0 can be converted to a pointer, and that will be the NULL
> > pointer, and a NULL pointer cast as an integer shall give the value
> > 0.
> The only one I have anything close to a copy of is C99, for which I
> have a very late draft.
> Based on that:
> You are not quite correct.  Any integer may be converted to a pointer,
> and any pointer may be converted to an integer - but the mapping is
> entirely implementation-dependent, except in the integer->pointer
> direction when the integer is a "null pointer constant", defined as
> "[a]n integer constant expression with the value 0" (or such an
> expression cast to void *, though not if we're talking specifically
> about integers), in which case "the resulting pointer, called a null
> pointer, is guaranteed to compare unequal to a pointer to any object or
> function".  You could have meant that, but what you wrote could also be
> taken as applying to the _run-time_ integer value 0, which C99's
> promise does not apply to.  (Quotes are from
> I don't think there is any promise that converting a null pointer of
> any type back to an integer will necessarily produce a zero integer.

The wording was the same for C89 and there is this paragraph in K&R
(second edition, p 102):

"Pointers and integers are not interchangeable. Zero is the sole
exception: the constant zero may be assigned to a pointer, and a pointer
may be compared with the constant zero. The symbolic constant NULL is
often used in place of zero, as a mnemonic to indicate more clearly that
this is a special value for a pointer. [...]"

I interpret this (the paragraph above and the standard) as: in comparing 
a pointer to the constant zero, the constant zero is converted to
a pointer of NULL value, thus comparing pointer to pointer and not
comparing an integer value (the integer value of the pointer) to
an integer value (0).

So defining NULL as the casting of 0 is (was?) in the C standard, the
actual value of the expression i.e. of an incorrect (NULL) pointer
being implementation defined.

        Thierry Laronde <tlaronde +AT+ polynum +dot+ com>
Key fingerprint = 0FF7 E906 FBAF FE95 FD89  250D 52B1 AE95 6006 F40C

Home | Main Index | Thread Index | Old Index