Is the following code safe if a null pointer is passed in?
if(ptr && *ptr == value)
{
//do something
}
Does the order of the checks
In addition to all the others answers about ptr && *ptr == value
being valid, but not the other way round, the notion of valid pointer may have different meaning.
The ptr
could be an uninitialized variable, or could be obtained (e.g. by a cast from some random intptr_t
integer) in such a way that it does not point anywhere (e.g. a dangling pointer) but is not null.
In that case, neither order of testing works.
Some pointers can be invalid and be non-null (then testing ptr && *ptr == value
is undefined behavior). There is no portable way to test them. (but you could use operating-system or processor specific tricks).