The null pointer value represents a well-defined "nowhere"; it is an invalid pointer value that is guaranteed to compare unequal to any other pointer value. Attempting to dereference a null pointer results in undefined behavior, and will usually lead to a runtime error, so you want to make sure a pointer is not NULL before attempting to dereference it. A number of C and C++ library functions will return a null pointer to indicate an error condition. For example, the library function malloc
will return a null pointer value if it cannot allocate the number of bytes that have been requested, and attempting to access memory through that pointer will (usually) lead to a runtime error:
int *p = malloc(sizeof *p * N);
p[0] = ...; // this will (usually) blow up if malloc returned NULL
So we need to make sure the malloc
call succeeded by checking the value of p
against NULL:
int *p = malloc(sizeof *p * N);
if (p != NULL) // or just if (p)
p[0] = ...;
Now, hang on to your socks a minute, this is going to get a bit bumpy.
There is a null pointer value and a null pointer constant, and the two are not necessarily the same. The null pointer value is whatever value the underlying architecture uses to represent "nowhere". This value may be 0x00000000, or 0xFFFFFFFF, or 0xDEADBEEF, or something completely different. Do not assume that the null pointer value is always 0.
The null pointer constant, OTOH, is always a 0-valued integral expression. As far as your source code is concerned, 0 (or any integral expression that evaluates to 0) represents a null pointer. Both C and C++ define the NULL macro as the null pointer constant. When your code is compiled, the null pointer constant will be replaced with the appropriate null pointer value in the generated machine code.
Also, be aware that NULL is only one of many possible invalid pointer values; if you declare an auto pointer variable without explicitly initializing it, such as
int *p;
the value initially stored in the variable is indeterminate, and may not correspond to a valid or accessible memory address. Unfortunately, there's no (portable) way to tell if a non-NULL pointer value is valid or not before attempting to use it. So if you're dealing with pointers, it's usually a good idea to explicitly initialize them to NULL when you declare them, and to set them to NULL when they're not actively pointing to anything.
Note that this is more of an issue in C than C++; idiomatic C++ shouldn't use pointers all that much.