Null Pointer, Oh No!

Khun Yee Fung, Ph.D.
Programming is Life
2 min readNov 4, 2023

Well, maybe?

A drawing of the NIL dotted pair in LISP, and how both cells point back to the NIL dotted pair.
The NIL dotted pair in LISP.

Tony Hoare was said to have said that he invented the null pointer, and that it was a billion dollar mistake.

Maybe.

I mean, maybe he said that, but maybe it is not a mistake to have the concept, just that the semantics is misplaced?

The idea of a null pointer has been around before the year 1964, said to be the year Hoare invented the null pointer. And it was really a simple idea. And you don’t get a null pointer exception because it is really not an exception.

You see, the NIL reference in LISP can be implemented as a dotted pair where both the HEAD (CAR) and the TAIL (CDR) point back to the NIL dotted pair. So, (CAR NIL) is NIL, and (CDR NIL) is also NIL. Granted you can get lost in it if you are not careful, perhaps an infinite recursive call, but it is not an exception.

What should be the semantics in a language like C? Well, not much. You see, C is a very low level language meant to reflect the hardware. If your philosophy of such a language is that it should be as close to the hardware as possible, then the NULL pointer, with the address of zero, should point to that address. Okay, so should the address zero be invalid or not? Actually, it does not have to be invalid. Some Unix implementations actually would dereference a NULL pointer quite readily without having a segmentation fault (invalid address reference). But officially, dereferencing a null pointer is not defined. So, do know how your OS handles this.

Ok, how about Java? Well, for whatever reason, Java does not want to handle null pointers in the most reasonable way. Namely, simply be null all the way down. Admittedly, Java has primitive types, and that complicates things. For all references though, it can easily simply specify that null pointer deferencing is good but it will be null.

class Pointer {
private Pointer left;
private Pointer right;

public static void main(String[] args) {
Pointer a = null;
System.out.println("What is pointed by left? ", a.left);
}
}

Sure, the current Java semantics says that ‘a.left’ causes a null pointer exception. But if we define that if a is null, then a.left is automatically null as well, there is no exception. Tons of useless checking will not be needed as well. For instance, ‘a.left.left.left’ is still null and not causing a null pointer exception.

In other words, there is no compelling reason why deferencing a null pointer has to be an exception. It is just defined to be such.

If LISP can do it in 1960, we can do it in 2023, right?

--

--

Khun Yee Fung, Ph.D.
Programming is Life

I am a computer programmer. Programming is a hobby and also part of my job as a CTO. I have been doing it for more than 40 years now.