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

后端 未结 4 1610
情书的邮戳
情书的邮戳 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 07:06

    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).

提交回复
热议问题