Is it safe to check if a pointer is null, then dereference it in the same if statement?

后端 未结 4 1639
情书的邮戳
情书的邮戳 2021-02-20 06:43

Is the following code safe if a null pointer is passed in?

if(ptr && *ptr == value)
{
   //do something
}

Does the order of the checks

4条回答
  •  长情又很酷
    2021-02-20 06:49

    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"

提交回复
热议问题