'Can the unary & operator yield the address 0 (null pointer)?
C2x, 6.5.3.2 Address and indirection operators, Semantics, 3:
The unary & operator yields the address of its operand.
A simple question: can the unary & operator yield the address 0 (null pointer)?
Any examples / experience?
Solution 1:[1]
It can. But you have to go out of your way to make it possible.
There are two ways to do this for an actual object:
Construct an object file or linker symbol file that you are linking against that exports a symbol at NULL. If you & on that you will get NULL.
Be libc on certain platforms. The first symbol you define is NULL. On at least one platform, the heap manager had to contend with this so it was carefully coded so the compiler would never observe the fact the heap HEAD pointer was stored at NULL.
Notice that both of these waaaay out of portable C, and that's the point. If you get & to return NULL you will know you did it. It's not happening by accident.
However there is another way: We can construct an expression containing no real objects where & returns a 0. Like this:
&(((struct some_struct *)0)->first_member)
Only seen in
#define offsetof(type, member) ((size_t)&(((type *)0)->member))
Don't do this. #include <stddef> and let the compiler define offsetof. There's a bug in this implementation.
Solution 2:[2]
The relevant section of the standard is 6.3.2.3/3 (N2731), which states
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.
Consequently, the result of & acting on any object is guaranteed to "compare unequal" with a null pointer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Brian |
