Trying to understand NULL pointers
C++ What are the NULL pointer values? - Stack Overflow
Define null pointer and its uses.
Checking for null pointers when 0 is a valid address
What is a null pointer?
Does a null pointer have a specific value in programming languages?
Can a null pointer be compared with other pointers?
Videos
Hello all again,
I have another stupid question here lol, so I'm trying to wrap my head around NULL. Im currently under the impression that NULL is a built in constant that has a value of zero, but what does that actually mean? When would it be appropriate to use null? If someone could explain it in layman's terms that would be super helpful!
The 0xCACACACA generated by Visual Studio is usually there for un-initialized pointers, for precisely this reason. When you see this, you know something is wrong. If it initialized it to 0, it can very well be expected behavior. This is only done in debug node, with full optimization the value of an uninitialized pointer would be just garbage.
And yes, NULL pointers don't have a value of 0 per say. 0 is just a literal. The actual value can be different. But the compiler is smart enough to abstract that away, so even if you have a NULL pointer whose value isn't really 0 (as in the number 0), comparing it to 0 or NULL would still yield true. It's better to think in terms of nullptr really.
This question previously appeared on the comp.lang.c newsgroup. You can read the archive with Google Groups
In that thread, Paul Sand quoted another source, "Portable C" by H. Rabinowitz and Chaim Schaap, as follows:
Certain Prime computers use a value different from all-bits-0 to encode the null pointer. Also, some large Honeywell-Bull machines use the bit pattern 06000 to encode the null pointer. On such machines, the assignment of
0to a pointer yields the special bit pattern that designates the null pointer.Similarly,
(char *)0yields the special bit pattern that designates a null pointer.
Where you'd commonly see non-null pointers is when working with physical memory addresses (that is, when there is no MMU or in kernel mode bypassing the MMU) and the machine has memory-mapped I/O at or near address 0. You want a null pointer to be way out in no-man's land, so that if you offset it (e.g. structure member access via a pointer) you won't get any useful address.
For your specific question, only an integral constant expression with value 0 is interpreted as a null pointer. So
char* p = (char*)i;
does not portably make p a null pointer (i.e. the Standard makes no such guarantee, but your particular compiler may).