Monday 7 November 2011

What is a null pointer? in C programming

What is a null pointer?

There are times (see FAQ VII.4) when it’s necessary to have a pointer that doesn’t point to anything. The
macro NULL, defined in <stddef.h>, has a value that’s guaranteed to be different from any valid pointer. NULL

is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather
than NULL.
You can’t use an integer when a pointer is required. The exception is that a literal zero value can be used as
the null pointer. (It doesn’t have to be a literal zero, but that’s the only useful case. Any expression that can
be evaluated at compile time, and that is zero, will do. It’s not good enough to have an integer variable that
might be zero at runtime.)

NOTE

The null pointer might not be stored as a zero; see FAQ VII.10.

WARNING

You should never go indirect on a null pointer. If you do, your program might get garbage, get a
value that’s all zeros, or halt gracelessly.

Cross Reference:

VII.4: When is a null pointer used?
VII.10: Is NULL always equal to 0?
VII.24: What is a “null pointer assignment” error? What are bus errors, memory faults, and core
dumps?

No comments:

Post a Comment