C Pointers – Difference Between Pointer to 0x0 Location and Pointer Set to NULL

cnullpointers

Is a pointer pointing to 0x0000 the same as a pointer set to NULL? If NULL value is defined in the C language, then what location does it physically translate to? Is it the same as 0x0000. Where can I find more details about these concepts?

Best Answer

A point that most of the answers here are not addressing, at least not explicitly, is that a null pointer is a value that exists during execution, and a null pointer constant is a syntactic construct that exists in C source code.

A null pointer constant, as Karlson's answer correctly states, is either an integer constant expression with the value 0 (a simple 0 is the most common example), or such an expression cast to void* (such as (void*)0).

NULL is a macro, defined in <stddef.h> and several other standard headers, that expands to an implementation-defined null pointer constant. The expansion is typically either 0 or ((void*)0) (the outer parentheses are needed to satisfy other language rules).

So a literal 0, when used in a context that requires an expression of pointer type, always evaluates to a null pointer, i.e., a unique pointer value that points to no object. That does not imply anything about the representation of a null pointer. Null pointers are very commonly represented as all-bits-zero, but they can be represented as anything. But even if a null pointer is represented as 0xDEADBEEF, 0 or (void*)0 is still a null pointer constant.

This answer to the question on stackoverflow covers this well.

This implies, among other things, that memset() or calloc(), which can set a region of memory to all-bits-zero, will not necessarily set any pointers in that region to null pointers. They're likely to do so on most implementations, perhaps even all existing ones, but the language doesn't guarantee it.

This question is really a duplicate of this one, but Stack Exchange doesn't allow marking duplicates across sites.