Search code examples
pointersnullnullpointerexceptionlow-level

On which level in a computer is the null pointer defined?


A raw computer basically just has memory with physical addresses starting at 0, right? Then someone could write assembly code (such as a BIOS) and actually put a value at 0.

Now if there is a BIOS that starts the computer, then someone could write a loader for an operating system. Can that person decide to move actual values to position 0 in the memory in assembly language?

What if they use C or C++? Can they have a pointer with value 0 and use it to access the first memory location? Does that need a specially adapted compiler?

And then the operating system enters the scene. It has a memory manager which is called by malloc to get more memory. Could an operating system be written which can simply use null pointers as normal pointers, but otherwise behaves exactly like Linux, and then if someone compiles a C program with a normal, unmodified GCC for it, a null pointer wouldn't lead to a segmentation fault?


Solution

  • The null pointer in C and similar languages is just a convention, to allow an easy to check for indication that a pointer doesn't point to anything valid. There is nothing in the computer that physically stops anything from storing data at memory location 0. In fact, the C standard doesn't even state that the null pointer must have all bits zero or correspond to memory location 0, just that it must be what you get from (void *)0.

    malloc and similar functions cannot return a null pointer as a valid memory location, because a return of a null pointer is specifically defined to indicate failure.

    Now, to support this extremely common usage of the null pointer in C, some operating systems will specifically not map or otherwise set a trap for the memory location corresponding to the null pointer so any accidental accesses will immediately raise a segmentation violation or the like. Operating systems do exist that do not do this, of course.