Assigning a reference by dereferencing a NULL pointer

半城伤御伤魂 提交于 2019-11-28 09:13:10

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.

When you dereference a null pointer, you don't necessarily get an exception; all that is guaranteed is that the behavior is undefined (which really means that there is no guarantee at all as to what the behavior is).

Once the *temp expression is evaluated, it is impossible to reason about the behavior of the program.

You are not allowed to dereference a null pointer, so the compiler can generate code assuming that you don't do that. If you do it anyway, the compiler might be nice and tell you, but it doesn't have to. It's your part of the contract that says you must not do it.

In this case, I bet the compiler will be nice and tell you the problem already at compile time, if you just set the warning level properly.

Don't * a null pointer, it's UB. (undefined behavior, you can never assume it'll do anything short of lighting your dog on fire and forcing you to take shrooms which will lead to FABULOUS anecdotes)

Some history and information of null pointers in the Algol/C family: http://en.wikipedia.org/wiki/Pointer_(computing)#Null_pointer

Examples and implications of undefined behavior: http://en.wikipedia.org/wiki/Undefined_behavior#Examples_in_C

I don't sure I understand what you're trying todo. Dereferencing of ** NULL** pointer is not defined.

In case you want to indicate that you method not always returns value you can declare it as:

bool fun(int &val);

or stl way (similar to std::map insert):

std::pair<int, bool> fun();

or boost way:

boost::optional<int> fun();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!