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