C standard compliant way to access null pointer address?

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

    Whatever solution is going to be implementation-dependent. Needfully. ISO C does not describe the environment a C programs runs on; rather, what a conforming C program looks like among a variety of environments («data-processing systems»). The Standard cannot indeed guarantee what you would get by accessing an address that is not an array of objects, i.e. something you visibly allocated, not the environment.

    Therefore, I would use something the standard leaves as implementation-defined (and even as conditionally-supported) rather than undefined behavior*: Inline assembly. For GCC/clang:

    asm volatile("movzx 0, %%eax;") // *(int*)0;
    

    It also worth mentioning freestanding environments, the one you seem to be in. The standard says about this execution model (emphasis mine):

    § 5.1.2

    Two execution environments are defined: freestanding and hosted. [...]

    § 5.1.2.1, comma 1

    In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined. Any library facilities available to a freestanding program, other than the minimal set required by clause 4, are implementation-defined. [...]

    Notice it doesn't say you can access any address at will.


    Whatever that could mean. Things are a bit different when you are the implementation the standard delegates control to.

    All quotes are from the draft N. 1570.

提交回复
热议问题