Consider:
struct T{};
int main() {
T* p = (T*)0xDEADBEEF;
}
Using an invalid pointer is implementation-defined. Dereferencing it is undefined behavior. My question isn't about those.
My question is whether the mere initialization of p
, as is, is defined.
If you think you already have all the information needed to answer this question (or if you found out that this is a duplicate), you need read no further. Following is some mumbling based on my findings:
The C standard (of which the C++ standard is based on) says:
6.3.2.3 Pointers
5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
Which hints it may be implementation defined.
The C++ Standard only defines (as far as I know) that any use of an invalid pointer value is implementation defined. The footnote is of special importance, as it seems to suggest that the mere copy of such value is already an use of the pointer. (Or does it mean the pointed-to value? I'm confused)
6.7 Storage duration
4 When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values (6.9.2). Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.37
37 Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault
This kind of agrees with the C standard. The problem is I'm not convinced this is an example of an invalid pointer value, as the standard clearly says this type of value is caused by the end of the duration of storage for that address being reached (which clearly never happened).
There are also many instances of pointer arithmetic that are Undefined BehaviourTM, but clearly no arithmetic or manipulation on the value of the pointer is being done here. This is merely an initialization.