Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is initializing a pointer declarator with an invalid pointer undefined behavior?

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:

  • A pointer to an object or function;
  • A pointer past the end of an object;
  • The null pointer value;
  • An invalid pointer value.

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.

like image 809
Mário Feroldi Avatar asked May 26 '18 19:05

Mário Feroldi


1 Answers

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.

like image 114
Davis Herring Avatar answered Oct 01 '22 14:10

Davis Herring