1

Possible Duplicate:
A reference can not be NULL or it can be NULL?

How does the below program compile successfully?

int main()
{
   int *ptr = NULL;
   int &ref = *ptr;
   return 0;
}

See it on ideone.

Can we define reference to NULL?

Community
  • 1
  • 1
Green goblin
  • 9,898
  • 13
  • 71
  • 100

4 Answers4

6

The code you've given will compile, because the compiler doesn't check the value of the pointer at compile-time. However dereferencing a NULL pointer is undefined behavior.

This is a problem that I ran into once in the past and was burned into my memory. My further thoughts can be found here: https://stackoverflow.com/a/57656/5987

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
4

Taken from the C++ FAQ:

The C++ language, as defined by the C++ standard, says it's illegal; that makes it illegal. The C++ standard does not require a diagnostic for this particular error, which means your particular compiler is not obliged to notice that p is NULL or to give an error message, but it's still illegal. The C++ language also does not require the compiler to generate code that would blow up at runtime.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Science_Fiction
  • 3,403
  • 23
  • 27
1

You dereference the null pointer. Your compiler is not mandated to complain such ill-formed program. That however doesn't imply that nothing bad could happen to you at the time of running this.

From C++03 8.3.2/4:

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.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
-3

No. ptr is a pointer that has an address. You set that pointer to null. So the value of that pointer is null. But the pointer itself has an address. The reference is being set to the address of the pointer - not to its value.

Now a reference to NULL itself - that would fail. e.g.:

int &ref = &NULL; // fail
Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59
  • 2
    Ad hominem attacks are not necessary. The question is about `int &ref = *ptr`, which is *not* setting the reference to the address of the pointer -- it's setting the reference to the value pointed to by the pointer, which does not exist in the case of a null pointer. `int *&ref = ptr` would create a reference to the pointer. The fact that `&NULL` doesn't compile is unrelated to the question at hand. – Adam Rosenfield Jul 31 '12 at 21:21