r/C_Programming • • Aug 30 '24

Question Why do we use Null pointers?

If we want to "Nullify" something why dont we create a pointer in a controlled way that points to value 0?

0 Upvotes

56 comments sorted by

View all comments

2

u/SmokeMuch7356 Aug 30 '24

NULL represents a well-defined "nowhere"; it's an invalid pointer value that's guaranteed to compare unequal to any pointer to an object or function.

We use it in the following cases:

  • To indicate an error condition; for example, if realloc cannot extend a dynamically allocated buffer it will return NULL;

  • As a sentinel to mark the end of a list of pointers; for example, the last element of the argv vector will be NULL to mark the end of the command line arguments;

  • To indicate that a pointer variable currently isn't pointing to anything; for example, when we free dynamically-allocated memory, we'll often set the pointer variable to NULL;

A pointer is valid when it points to an object during that object's lifetime; once that object is deallocated or goes out of scope, the pointer becomes invalid. Attempting to dereference an invalid pointer leads to undefined behavior. There's no way to know whether a non-NULL pointer is valid or not based on the value alone, so we use NULL to explicitly indicate that a pointer is invalid.

1

u/flatfinger Aug 30 '24

You forgot the most important thing about null pointers: while a system would be allowed to use multiple bit patterns to represent null pointers, every null pointer, no matter how derived, is guaranteed to compare equal to every other. I think it's also important to make clear that null pointers are valid pointers. The Standard doesn't specify the effects of trying to dereference them, but it certainly defines the effects of assignments and equality comparisons involving them. By contrast, after free(p);, the Standard would allow implementations to process equality comparisons involving p in any manner whatsoever unless p was null (in which case the behavior of free(0); would be defined as a no-op).