Is the following code safe if a null pointer is passed in?
if(ptr && *ptr == value)
{
//do something
}
Does the order of the checks
Yes (1) is safe because of short circuiting. This is the way that the logical statement is evaluated. If the first part of the &&
statement is false then the whole statement can never be true so it will not try to evaluate the second part.
and (2) is unsafe because it dereferences the null pointer first, which is undefined behaviour.
edit:
in reference to KerrekSBs comment below: Why dereferencing a null pointer is undefined behaviour?
From the first answer in that post:
Defining consistent behavior for dereferencing a NULL pointer would require the compiler to check for NULL pointers before each dereference on most CPU architectures. This is an unacceptable burdern for a language that is designed for speed.
Also there is (was historically) hardware where the memory pointed to by NULL
(not always 0
) is in fact addressable within the program and can be dereferenced. So because of a lack of consensus and consistency it was decided that dereferencing a null pointer would be "undefined behaviour"