Why p && *p
prevents null pointer dereference?
How can I use the expression to prevent the dereference?

- 129
- 1
- 8
-
What do you mean by "How can I use the expression to prevent the dereference?" ? Seems `p && *p` itself is an arbitrary example of how you might be able to prevent a null pointer dereference. – George Jan 06 '19 at 05:42
-
As I see, it's a condition but I cannot realize in why it should be true in case `p!=NULL` – cellka Jan 06 '19 at 05:45
-
Oh, probably I forgot that in C any Nonzero value is true in Boolean logic – cellka Jan 06 '19 at 05:49
2 Answers
From C Standard#6.3.2.3p3
3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
...
...Footnotes
66) The macro NULL is defined in (and other headers) as a null pointer constant; see 7.19.
Logical AND
operation expr1 && expr2
employs short-circuiting behavior. With logical short-circuiting, the second operand, expr2
, is evaluated only when the result is not fully determined by the first operand, expr1
.
That is, expr2
is not evaluated if expr1
is logical 0
(false).
If p
is a NULL
pointer then it will be evaluated as 0
and due to short-circuiting behavior of &&
operator *p
will not be evaluated. Thats how p && *p
prevents null pointer dereference.

- 11,654
- 2
- 15
- 32
Here
p && *p
| |
first second
operand operand
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 fact that p = NULL
means p
is pointing to NULL
hence one shouldn't do *p
as it causes segmentation fault. For e.g
int *p = NULL;
if (!p ) {
fprintf(stderr,"p is NULL, can't do further opertaion with p\n");
exit(0);
}
else {
/* further processing with p i.e p is valid and *p is not zero */
}

- 11,821
- 2
- 15
- 37
-
Well, if `p = NULL` then we go into else statement with NULL pointer, so no prevention – cellka Jan 06 '19 at 12:12
-
Yes true . I put the check reversely. My bad. I will edit as soon I have my system. – Achal Jan 06 '19 at 12:58
-
I was playing around with that example and I noticed that if we set `int x = 0; int *p = &x;` then the code considers p as null-pointer. So, if we point to a variable the value of which is 0 at the moment, then we cannot work with the code further – cellka Jan 06 '19 at 13:30