Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...