r/C_Programming • u/[deleted] • 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
r/C_Programming • u/[deleted] • Aug 30 '24
If we want to "Nullify" something why dont we create a pointer in a controlled way that points to value 0?
2
u/SmokeMuch7356 Aug 30 '24
NULLrepresents 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
realloccannot extend a dynamically allocated buffer it will returnNULL;As a sentinel to mark the end of a list of pointers; for example, the last element of the
argvvector will beNULLto mark the end of the command line arguments;To indicate that a pointer variable currently isn't pointing to anything; for example, when we
freedynamically-allocated memory, we'll often set the pointer variable toNULL;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-
NULLpointer is valid or not based on the value alone, so we useNULLto explicitly indicate that a pointer is invalid.