In short, is the following code considered to have undefined behavior?
int main()
{
int *p = <some invalid pointer value>;
}
For a compiling example, take the following code:
int main()
{
int *p = new int;
delete p; // Now p has an invalid pointer value.
int *q = p; // UB?
}
I've done some research on the topic, so these are the relevant information I've found so far:
A pointer value (according to cppreference) can be one of:
Also, according to cppreference,
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.
This thread addresses some uses of invalid pointers. Specifically, this answer mentions the Rationale document (C99), which has the following paragraph (section 6.3.2.3):
Regardless how an invalid pointer is created, any use of it yields undefined behavior. Even assignment, comparison with a null pointer constant, or comparison with itself, might on some systems result in an exception.
I'm not sure what's the state of affairs for C++, but I'd consider that, given the answers on the linked thread, uses of invalid pointers result in undefined behavior. Note, though, that assignment is not the same as initialization, so I'm not sure initialization is considered a use.
You’ve all but answered this yourself: it’s implementation defined, not undefined, in C++. The standard says just what you quoted (which I found by consulting the appropriate index). It doesn’t matter whether it’s initialization: the lvalue-to-rvalue conversion on the pointer object explicitly constitutes a use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With