In C, what is the difference between a NULL pointer and a pointer that points to 0?
5 Answers
The ISO/IEC 9899:TC2 states in 6.3.2.3 Pointers
3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function
The macro NULL expands to an implementation-defined null pointer constant.
Any two null pointers shall compare equal.
Comments
Yes there is. The standard dictates that NULL always points to invalid memory. But it does not state that the integer representation of the pointer must be 0. I've never come across an implementation for which NULL was other than 0, but that is not mandated by the standard.
Note that assigning the literal 0 to a pointer does not mean that the pointer assumes the integer representation of 0. It means that the special null pointer value is assigned to the pointer variable.
6 Comments
int *ptr = 0; always results in a null pointer thanks to a special rule, because 0 is a so-called "null pointer constant". This holds even if you're on some peculiar implementation where a null pointer is different from address 0. However, int i = 0; int *ptr = (int*)i; does not necessarily result in a null pointer. So you won't normally encounter "a pointer that points to the 0 address" except in a context where it is a null pointer, but the standard permits it.NULL is always a 0 value by definition of the standard, which might be a valid address, e.g in the kernel. So one should better distinguish NULL more clearly from the internal representation of a null pointer, which, as you say could be something different.int *ptr = (int *)(0,0); yields a null pointer (since (0,0) is not specified to be an integer constant expression, but may be an additional implementation-defined integer constant expression).(0,0) isn't really code, it's a little owl.NULL is not necessarily a 0 value, it could be (void*)0, which is a null pointer value. If a null pointer refers to a valid object in the kernel, then the kernel isn't a conforming C environment (hence that painful bug with -fdelete-null-pointer-checks), since the standard guarantees that a null pointer compares unequal to any pointer to an object.The old comp.lang.c FAQ has a big section on the null pointer and it's worth a read.
Comments
The idea is that a NULL pointer should somehow represent a memory area that is invalid.
So since in the lower memory segments the OS code is mapped, the value of 0 has been used (to represent the NULL pointer) since this area in memory does not belong to the user's program but is mapped to the OS code.