Partha Bera Partha Bera - 3 months ago 14
C Question

Why no segfault on null pointer dereference?

I have written this simple C code,

int main()
{
int *p = NULL;
if (p && *p);
//if (*p && p);
return 0;
}


When I run this code, unexpectedly I didn't any seg fault. But if I change order of
p
and
*p
in
if ()
(like in the comment) I do get seg fault.

Can someone explain why?

Answer

The && operator has short-circuit evaluation. If the result can be determined by just looking at the value of the left operand, then the right operand is not evaluated. For the && operator, this means that if the left side evaluates to false, it doesn't evaluate the right side, and the result is false. In other words,

if (p && *p) ...

is equivalent to

if (p) if (*p) ...

From the C11 standard, section 6.5.13/4:

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

Comments