Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a reference by dereferencing a NULL pointer

int&  fun()
{
    int * temp = NULL;
    return *temp;
}

In the above method, I am trying to do the dereferencing of a NULL pointer. When I call this function it does not give exception. I found when return type is by reference it does not give exception if it is by value then it does. Even when dereferencing of NULL pointer is assinged to reference (like the below line) then also it does not give.

int* temp = NULL:
int& temp1 = *temp;

Here my question is that does not compiler do the dereferencing in case of reference?

like image 671
G Mann Avatar asked Jul 16 '11 07:07

G Mann


People also ask

What happens if I dereference a null pointer?

CWE-476: NULL Pointer Dereference: A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.

Can you dereference a null pointer?

Dereferencing a null pointer always results in undefined behavior and can cause crashes. If the compiler finds a pointer dereference, it treats that pointer as nonnull. As a result, the optimizer may remove null equality checks for dereferenced pointers.

How do I stop null pointer dereference in C++?

H.S. Show activity on this post. first p is performed that means if p is NULL then it won't do *p as logical AND && operator property is that if first operand is false then don't check/evaluate second operand, hence it prevents null pointer dereference.

What does it mean to dereference a pointer?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.


1 Answers

Dereferencing a null pointer is Undefined Behavior.

An Undefined Behavior means anything can happen, So it is not possible to define a behavior for this.

Admittedly, I am going to add this C++ standard quote for the nth time, but seems it needs to be.

Regarding Undefined Behavior,

C++ Standard section 1.3.24 states:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

NOTE:
Also, just to bring it to your notice:
Using a returned reference or pointer to a local variable inside a function is also an Undefined Behavior. You should be allocating the pointer on freestore(heap) using new and then returning a reference/pointer to it.

EDIT:
As @James McNellis, appropriately points out in the comments,
If the returned pointer or reference is not used, the behavior is well defined.

like image 154
Alok Save Avatar answered Oct 20 '22 01:10

Alok Save