Remix.run Logo
wizzwizz4 4 hours ago

> Programmers like being able to null out a pointer field, 0 is an obvious "joker" value, and jump-if-0 instructions tend to be convenient and fast.

And there's nothing wrong with that! But you should write it

  union {
    char *ptr;
    size_t scalar;
  } my_nullable_pointer;
  if (my_nullable_pointer.scalar) {
    printf("%s", my_nullable_pointer.ptr);
  }
not:

  char *my_nullable_pointer;
  if (my_nullable_pointer) {
    printf("%s", my_nullable_pointer);
  }
Yes, this takes up more space, but it also makes the meaning of the code clearer. typedef in a header can bring this down to four extra lines per pointer type in the entire program. Add a macro, and it's five extra lines plus one extra line per pointer type. Put this in the standard library, and the programmer has to type a few extra characters – in exchange for it becoming extremely obvious (to an experienced programmer, or a quick-and-dirty linter) when someone's introduced a null pointer dereference, and when a flawed design makes null pointer dereferences inevitable.

> The Hoare ALGOL W thing seems to be more relevant to null pointers in Java and the like.

I believe you are correct; but I like blaming Tony Hoare for things. He keeps scooping me: I come up with something cool, and then Tony Hoare goes and takes credit for it 50 years in the past. Who does he think he is, Euler?