Anycorn
Anycorn

Reputation: 51465

C++ standard question

should the following result in undefined behavior?

should value of pointer2 be NULL?

double *pointer = 0;
double &value = *pointer;
double *pointer2 = &value;

Upvotes: 0

Views: 191

Answers (2)

Michael Burr
Michael Burr

Reputation: 340208

Yes.

double *pointer = 0;    // init `pointer` to a NULL pointer value
double &value = *pointer; // dereference it

The standard specifically speaks to this situation - from 8.3.2/4 "References":

A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]

Upvotes: 6

sepp2k
sepp2k

Reputation: 370162

Yes, you're dereferencing a null pointer when you do *pointer in line 2.

Upvotes: 3

Related Questions