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.
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. Extended Description. NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.
Dereferencing a null pointer is undefined behavior. On many platforms, dereferencing a null pointer results in abnormal program termination, but this is not required by the standard.
In practice, dereferencing a null pointer may result in an attempted read or write from memory that is not mapped, triggering a segmentation fault or memory access violation. This may manifest itself as a program crash, or be transformed into a software exception that can be caught by program code.
H.S. Show activity on this post. first p is performed that means if p is NULL then it won't do *p as logical AND && operator property is that if first operand is false then don't check/evaluate second operand, hence it prevents null pointer dereference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With