Is the following code safe if a null pointer is passed in?
if(ptr && *ptr == value)
{
//do something
}
Does the order of the checks matter? Does it work if I change it to this?
if(*ptr == value && ptr)
{
//do something
}
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.
It's good practice to check for null in function parameters and other places you may be dealing with pointers someone else is passing you. However, in your own code, you might have pointers you know will always be pointing to a valid object, so a null check is probably overkill... just use your common sense.
There are a few ways to avoid null pointer dereferences. One is to use a language that does not allow them, such as Java. Another is to always check pointers for NULL before dereferencing them.
The program can potentially dereference a null pointer, thereby raising a NullPointerException. Null pointer errors are usually the result of one or more programmer assumptions being violated.
The former is correct and safe, the latter is not.
The built-in &&
operator has short-circuit semantics, meaning that the second argument is evaluated if and only if the first one is true.
(This is not the case for overloaded operators.)
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"
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