tech-kern archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: NULL pointer arithmetic issues
On Mon, Mar 9, 2020 at 11:51 AM Martin Husemann <martin%duskware.de@localhost> wrote:
>
> On Mon, Mar 09, 2020 at 09:38:31AM -0400, Aaron Ballman wrote:
> > The way I read this is:
> >
> > "If the pointer operand points to an element of an array object" -- it
> > does not (null is not a valid array object).
> > "Moreover, if the expression P points to the last element of an array
> > object" -- it does not (null is not a valid array object).
> > "If both the pointer operand and the result point to elements of the
> > same array object, or one past the last element of the array
> > object..." -- it does not (there is no valid array so they cannot
> > point to elements of the same array).
>
> All fine.
>
> > "...otherwise, the behavior is undefined." -- this is where we hit the UB.
>
> But it started with "If the pointer operand points to an element of an
> array object" and my reading is that the whole section does not apply.
I don't think that's the correct predicate to read. The full sentence
I reach is:
"If both the pointer operand and the result point to elements of the
same array object, or one past the last element of the array object,
the evaluation shall not produce an overflow; otherwise, the behavior
is undefined."
The pointer operand and the result do not point to elements of the
same array object or one past the last element, so I hit the
"otherwise" case. But even under your interpretation, I see the result
as being UB -- anything the standard doesn't explicitly specify is
also undefined behavior, so if the whole section doesn't apply,
nothing else specifies the behavior.
> NULL is special, and we did not change it's value, so it stays a NULL
> pointer. The section you cited just does not tell anything about arithmetic
> on NULL pointers - and the wording makes it sound like this is more an
> oversight than a concious descision.
That was why I asked on the reflectors; there was sufficient confusion
from people reading the standard to warrant asking "are we reading
this properly" and the answer was: yes, we are interpreting it
properly and that NULL + 0 is UB.
> Eespecially adding or subtracting zero.
>
> You could view NULL as a special pointer pointing to an inaccessible
> zero sized object. Adding 0 to it still points to the same special
> non-object. I guess that is how the C++ folks see it.
This wording has always been UB in C. It stopped being UB in C++20 but
was UB prior to that. I did not see a core issue pertaining to this
(though it's possible I've missed it -- the C++ core issues list is a
bit hard to track these days), so I am not certain why this change was
made so recently.
~~Aaron
>
>
> Martin
Home |
Main Index |
Thread Index |
Old Index