C standard compliant way to access null pointer address?

后端 未结 5 1774
天命终不由人
天命终不由人 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 13:52

    The C Standard does not require that implementations have addresses that resemble integers in any way shape or form; all it requires is that if types uintptr_t and intptr_t exist, the act of converting a pointer to uintptr_t or intptr_t will yield a number, and converting that number directly back to the same type as the original pointer will yield a pointer equal to the original.

    While it is recommended that platforms which use addresses that resemble integers should define conversions between integers and addresses in a fashion that would be unsurprising to someone familiar with such mapping, that is not a requirement, and code relying upon such a recommendation would not be strictly conforming.

    Nonetheless, I would suggest that if a quality implementation specifies that it performs integer-to-pointer conversion by a simple bitwise mapping, and if there may be plausible reasons why code would want to access address zero, a it should regard statements like:

    *((uint32_t volatile*)0) = 0x12345678;
    *((uint32_t volatile*)x) = 0x12345678;
    

    as a request to write to address zero and address x, in that order even if x happens to be zero, and even if the implementation would normally trap on null pointer accesses. Such behavior isn't "standard", insofar as the Standard says nothing about the mapping between pointers and integers, but a good quality implementation should nonetheless behave sensibly.

提交回复
热议问题