int* p = 0;
int* q = &*p;
Is this undefined behavior or not? I browsed some related questions, but this specific aspect didn\'t show up.
The answer to this question is: it depends which language standard you are following :-).
In C90 and C++, this is not valid because you perform indirection on the null pointer (by doing *p
), and doing so results in undefined behavior.
However, in C99, this is valid, well-formed, and well-defined. In C99, if the operand of the unary-&
was obtained as the result of applying the unary-*
or by performing subscripting ([]
), then neither the &
nor the *
or []
is applied. For example:
int* p = 0;
int* q = &*p; // In C99, this is equivalent to int* q = p;
Likewise,
int* p = 0;
int* q = &p[0]; // In C99, this is equivalent to int* q = p + 0;
From C99 §6.5.3.2/3:
If the operand [of the unary
&
operator] is the result of a unary*
operator, neither that operator nor the&
operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.Similarly, if the operand is the result of a
[]
operator, neither the&
operator nor the unary*
that is implied by the[]
is evaluated and the result is as if the&
operator were removed and the[]
operator were changed to a+
operator.
(and its footnote, #84):
Thus,
&*E
is equivalent toE
(even ifE
is a null pointer)
Yes that would be undefined behavior, but your compiler might optimize the &*
out.
Why it its undefined, is that you are attempting to access memory outside your addressable space.
Yes, dereferencing the null pointer is undefined behavior. Integer constant 0 in a pointer context is the null pointer. That's it.
Now, if your second line was int *q = p;
that would be a simple pointer assignment. If the compiler removes the &*
and reduces the dereference to an assignment, you're OK.
IMHO, As far as the two code lines are concerned, there isn't any access outside the address space. The second statement is simply taking the address of (*p) which would be 'p' again and hence it will store '0'. But the location is never accessed.