C standard compliant way to access null pointer address?

后端 未结 5 1756
天命终不由人
天命终不由人 2020-12-28 13:23

In C, deferencing the null pointer is Undefined Behavior, however the null pointer value has a bit representation that in some architectures make it points to a val

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 14:12

    I'm assuming the question you are asking is:

    How do I access memory such that a pointer to that memory has the same representation as the null pointer?

    According to a literal reading of the Standard, this is not possible. 6.3.2.3/3 says that any pointer to an object must compare unequal to the null pointer.

    Therefore this pointer we are talking about must not point to an object. But the deference operator *, applied to an object pointer, only specifies the behaviour in the case that it points to an object.


    Having said that, the object model in C has never been specified rigorously, so I would not put too much weight into the above interpretation. Nevertheless, it seems to me that whatever solution you come up with is going to have to rely on non-standard behaviour from whichever compiler is in use.

    We see an example of this in the other answers in which gcc's optimizer detects an all-bits-zero pointer at a late stage of processing and flags it as UB.

提交回复
热议问题