tags:

views:

135

answers:

2

should the following result in undefined behavior?

should value of pointer2 be NULL?

double *pointer = 0;
double &value = *pointer;
double *pointer2 = &value;
+5  A: 

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. ]

Michael Burr
does it matter that I do not read/write to the memory location per se?
aaa
@aaa: Not as far as the standard is concerned.
sepp2k
You might not have a crash at that point because the compiler might not actually try to 'read' memory location 0. However, that's one of the unfortunate natures of undefined behavior - the compiler doesn't have to act like it's an error. Even so, setting a reference via a NULL pointer dereference is undefined behavior.
Michael Burr
+3  A: 

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

sepp2k