Static analysis flagged this code as nullPointerArithmetic:
static_cast<BYTE*>(NULL) + p_row_fields->offsets.back(), // field offset
where NULL is defined as #define NULL 0
and offsets resolves through typedef to std::vector<int>
The line in question is passed as a BYTE* argument to a method call.
My question is - What could be the purpose of this idiom?
Is there any difference between what's shown and the less eclectic direct cast:
static_cast<BYTE*>(p_row_fields->offsets.back())
Null pointer constant converts to any pointer type, resulting in null pointer value of that pointer type. Thus,
static_cast<BYTE*>(NULL)
yields a null pointer of typeBYTE*
. This conversion works implicitly as well.Strictly speaking, the behaviour of the pointer arithmetic on null is undefined by the standard because (or assuming that) there is no array at the null address.
As far as what the behaviour might be in practice assuming the compiler allows this, one might expect it to behave same as :
While this is not UB, there is still technically no standard guarantee that the resulting address is what was intended.
Yes, there is a difference. Of integer expressions, only compile time constant prvalues with value 0 are convertible to pointer types. Values other than 0, and lvalues such as
p_row_fields->offsets.back()
can not be static-casted to pointers.As such, the quoted cast is ill-formed.