Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a null reference?

Tags:

c++

Lets say you have something like this:

int& refint;
int* foo =0;
refint = *foo;

How could you verify if the reference is NULL to avoid a crash?

like image 381
jmasterx Avatar asked Nov 24 '10 19:11

jmasterx


People also ask

What is the meaning of null reference?

In computing, a null pointer or null reference is a value saved for indicating that the pointer or reference does not refer to a valid object.

How do you know if a reference is valid?

There is no way to know if your reference is referencing valid memory except by taking care of how you use references. For example you don't want to use a reference with something created on the heap if you are unsure when the memory will be deleted.


2 Answers

You can't late-initialize a reference like that. It has to be initialized when it's declared.

On Visual C++ I get

error C2530: 'refint' : references must be initialized

with your code.

If you 'fix' the code, the crash (strictly, undefined behaviour) happens at reference usage time in VC++ v10.

int* foo = 0;
int& refint(*foo);
int i(refint);  // access violation here

The way to make this safe is to check the pointer at reference initialization or assignment time.

int* foo =0;
if (foo)
{
  int& refint(*foo);
  int i(refint);
}

though that still does not guarantee foo points to usable memory, nor that it remains so while the reference is in scope.

like image 177
Steve Townsend Avatar answered Oct 15 '22 20:10

Steve Townsend


You don't, by the time you have a "null" reference you already have undefined behaviour. You should always check whether a pointer is null before trying to form a reference by dereferencing the pointer.

(Your code is illegal; you can't create an uninitialized reference and try and bind it by assigning it; you can only bind it during initialization.)

like image 36
CB Bailey Avatar answered Oct 15 '22 20:10

CB Bailey