Null Pointers

The null pointer in C is a bit of an odd beast. It’s a pointer that doesn’t point to anything. Specifically, it doesn’t point to an object in memory and it doesn’t point to a function either.

Now, you might think that’s what you get when you first declare a pointer i.e. the statement int *ptr; creates a null pointer. In fact it probably doesn’t. Instead, it creates an uninitialised pointer, essentially a pointer with a value (N.B. not a pointee) set to whatever happens to be in the memory where it is created. Those contents could have a value that points to somewhere in memory or they could have a value that represents the null pointer. So what does a null pointer representation look like?

According the C standard NULL must be defined to be either a zero valued integer constant or such a constant cast to void *. In other words NULL can be defined as either 0, 0L or (void *) 0. Interestingly, there may be a variety of null pointers, one for each pointer type, but as far as your C code is concerned, null pointers are represented by the value zero.

What happens when you try to dereference a null pointer, as in int *ptr = NULL; int val = *ptr;? Bad things. You’ll get a run-time error. But this is a good thing in many ways. What you really don’t want to be doing is dereferencing an uninitialised pointer, because they contain garbage and dereferencing that will probably just give you more garbage and operating on garbage, and random, non-repeatable garbage at that, will often give you silently erroneous execution that can cause all sorts of functionality issues.

Leave a Reply

Your email address will not be published. Required fields are marked *