I noticed this warning from Clang:
warning: performing pointer arithmetic on a null pointer
has undefined behavior [-Wnull-pointer-arithmetic]
In details, it is this code which triggers this warning:
uint8_t *end = ((uint8_t*)0) + sizeof(uint8_t) * count;
Why would arithmetic on a null pointer be forbidden when doing the same on a non-null pointer obtained from an integer different than zero does not trigger any warning ?
And more importantly, does the C standard explicitly forbid null pointer arithmetic ?
The C standard does not allow it.
For the purposes of the above, a pointer to a single object is considered as pointing into an array of 1 element.
Now,
((uint8_t*)0)
does not point at an element of an array object. Simply because a pointer holding a null pointer value does not point at any object. Which is said at:So you can't do arithmetic on it. The warning is justified, because as the second highlighted sentence mentions, we are in the case of undefined behavior.
Don't be fooled by the fact the
offsetof
macro is possibly implemented like that. The standard library is not bound by the constraints placed on user programs. It can employ deeper knowledge. But doing this in our code is not well defined.Little clarification on this thread.
First of all, this is undefined behavior per the C standard for the reasons cited by StoryTeller:
Since the zero constant literal converted to any pointer type decays into the null pointer constant, which does not point to any contiguous area of memory, the behavior is undefined.
However, performing arithmetic operations on null pointers in order to retrieve offsets is not new, the C implementation of the
offsetof
macro uses it:And doing the same arithmetic fashion on pointers is also frequent:
This line is virtually the same as writing:
I believe the offset calculation is implementation defined, as the compiler “could” dereference such pointers in order to retrieve the actual memory offset, which is of course very improbable, but still possible.
Also, note that this warning for null pointer arithmetic is specific to Clang 6.0. GCC does not trigger it even with
-fsanitize=undefined
.