Home > Software design >  Is a pointer to address 0 always invalid?
Is a pointer to address 0 always invalid?

Time:09-30

Is a pointer, which points to 0 always invalid? The addresses are used for very specific things, right? So if a developer tried to define a pointer to a variable in his scope, it should always be invalid, right?

int main() {
    int *ptr = (int *)0;
}

Is the address 0x0000 protected?

The reason I am asking is, because I have a struct with a union, and the values of the union can either be a double equal to 0, or a pointer to another struct.

CodePudding user response:

Simplifying:

This pointer is called NULL pointer and it is valid. Invalid is to dereference it.

Bear in mind that not every operation which looks like dereferencing is actually dereferencing and is invalid.

int *p = NULL;

size_t psize = sizeof(*p);  // valid, it is not dereferencing.

int x = *p; // invalid

Some very low-level programming requires reading or writing to the address 0 converted to the pointer.

uint32_t initial_stack_pointer = *(volatile uint32_t *)0UL;

It reads the initial (boot) value of the stack register from the Cortex-M vector table.

CodePudding user response:

In practice, in 2021, an address with all zero bits is invalid and practically is the NULL pointer (on laptops, desktops, supercomputers).

In theory, this is false (e.g. C compilers in the previous century for the Intel 286 processors had pointers of different width than int or long). Read for example the n1570 C standard.

The reason I am asking is, because I have a struct with a union, and the values of the union can either be a double equal to 0, or a pointer to another struct.

This will work on all the computers I have access to (in 2021).

But you could try static source code analyzers like Frama-C (or perhaps look into Bismon, or the DECODER project).

For C on microcontrollers like AVR or 8051, things are different. The all zero bits address could be dereferenced

  • Related