Reputation: 1162
Does NULL pointer take any memory? If it takes memory,then how much memory is consumed by it and what is the significant use of NULL pointer if it takes memory?
Upvotes: 5
Views: 4270
Reputation: 123548
A pointer value (NULL
or not) requires some amount of space to store and represent (4 to 8 bytes on most modern desktop systems, but could be some oddball size depending on the architecture).
The pointer value NULL
represents a well-defined "nowhere"; it's an invalid pointer value guaranteed to compare unequal to the address of any object or function in memory. The macro NULL
is set to the null pointer constant, which is a zero-valued integer expression (either a naked 0
, or (void *) 0
, or some other expression that evaluates to 0
).
After the code has been compiled, the null pointer constant will be replaced with the appropriate null pointer value for that particular platform (which may be 0x00000000
, or 0xFFFFFFFF
, or 0xDEADBEEF
, or some other value).
Upvotes: 10
Reputation: 180978
Any pointer value, including NULL
, takes a small, system-dependent amount of space to express or store.
That's an altogether separate consideration from any space that the pointed-to object, if any, may require. A NULL
pointer is guaranteed to not point to any object, but a non-NULL
pointer is not guaranteed to point to an object. On the other hand, there may be more than one pointer to the same object.
Where a NULL
pointer is intentionally used, it is typically used to explicitly express an invalid pointer, since you cannot tell from any other pointer value whether that pointer is valid. This can be useful, for example, as a sentinel value marking the end of an unknown-length array of pointers, or as a function return value indicating failure. The canonical example of the latter might be malloc()
, which returns NULL
if it fails to allocate the requested space.
Upvotes: 5
Reputation: 224377
A NULL
pointer doesn't allocate anything. If you have a definition like this:
int *x = NULL;
That means the variable x
, which points to an int
, doesn't point to anything. You can then check if (x == NULL)
to see if it points to valid memory.
Upvotes: 3