Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ standard: dereferencing NULL pointer to get a reference? [duplicate]

I'm wondering about what the C++ standard says about code like this:

int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref; 

In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard?
Under different circumstances a dereferencing of a NULL pointer should result in a crash but here I'm dereferencing it to get a reference which is implemented by the compiler as a pointer so there's really no actual dereferencing of NULL.

like image 468
shoosh Avatar asked Apr 28 '10 08:04

shoosh


People also ask

What happens if you dereference a NULL pointer in C?

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.

Does dereferencing a pointer make a copy?

Dereferencing sometimes makes a copy if we do more than dereferencing. Hence, if we use that dereferenced value to initialize a new variable, that is a copy, as shown in the above example.

What is null dereferencing error?

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. Extended Description. NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.

What is null pointer vulnerability?

ABSTRACT Null pointer dereference (NPD) is a widespread vulnerability that occurs whenever an executing program attempts to dereference a null pointer. NPD vulnerability can be exploited by hackers to maliciously crash a process to cause a denial of service or execute an arbitrary code under specific conditions.


1 Answers

Dereferencing a NULL pointer is undefined behavior.

In fact the standard calls this exact situation out in a note (8.3.2/4 "References"):

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.


As an aside: The one time I'm aware of that a NULL pointer can be "dereferenced" in a well-defined way is as the operand to the sizeof operator, because the operand to sizeof isn't actually evaluated (so the dereference never actually occurs).

like image 143
Michael Burr Avatar answered Sep 28 '22 19:09

Michael Burr