Home > OS >  Accessing the content at memeory address 0x0 will result in an undefined behavior?
Accessing the content at memeory address 0x0 will result in an undefined behavior?

Time:09-08

I tried to access memory address 0, which is defined as the start address of my ROM, to check that my configuration is correct and such region is accessible. But when I compile the code, the resulting disassembly shows that such operation is undefined.

It's true that 0 is NULL and might be treated as undefined, but is there any workaround for accessing the content at memory address 0?

Here is the test code:

#include <stdio.h>
int main ()
{
    printf("X", *(unsigned int*)(0));
}

When compiled with arm gcc and option -Os, the resulting disassembly is got.

main:
        mov     r3, #0
        ldr     r3, [r3]
        .inst   0xe7f000f0

It can be seen that the code ends at .inst 0xe7f000f0 and printf is not called.

The code can also be found Compiler Explorer.

CodePudding user response:

The easiest way is to map an object at absolute addess zero through your linker script and then access that object, instead of trying to create a pointer to address zero.

For ARM Cortex M it is very likely that the tool chain has already done this for you, in the form of the vector table special registers from address zero and upwards. Simply use the identifiers provided by the tool chain instead, or in the unlikely event that such aren't available, make your own custom linker script and allocate variables at physical address 0.


As for the "language-lawyer" part of the question:

It's true that 0 is NULL and might be treated as undefined, but is there any workaround for accessing the content at memory address 0?

Not exactly. NULL is a null pointer constant, 0 is a null pointer constant and either of those can be used to create a null pointer, like in your code when you cast 0 to an object pointer type.

See What's the difference between null pointers and NULL? where I try to clear up the difference between null pointers, null pointer constants and the NULL macro.

As for dereferencing a null pointer, it is undefined behavior as per the spec for the unary * operator, 6.5.3/4:

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined

  • Related