Can You Dereference a NULL Pointer to Acquire a Reference?
The C standard defines dereferencing a NULL pointer as undefined behavior. However, code snippets involving NULL pointer dereferencing to obtain a reference, such as the following, raise questions:
int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref;
Standard Definition:
According to the C standard (8.3.2/4 "References"), a null reference cannot exist in a well-defined program. This is because creating such a reference would require binding it to the "object" obtained by dereferencing a null pointer, which constitutes undefined behavior.
Implementation Detail or Well-Defined?
In practice, the code snippet provided results in ptr2 being set to NULL. However, this is merely an implementation detail. The standard explicitly states that dereferencing a null pointer is undefined.
Impact of Dereferencing a NULL Pointer:
In general, dereferencing a null pointer leads to a crash. In the specific case of using it to obtain a reference, the compiler implements the reference as a pointer, eliminating the actual dereference operation. Nevertheless, the underlying undefined behavior remains.
Exception: The sizeof Operator
The exception to dereferencing a null pointer in a well-defined manner is the sizeof operator. When using sizeof, the operand is not evaluated, avoiding the dereference operation.
The above is the detailed content of Can Dereferencing a NULL Pointer to Get a Reference Be Well-Defined in C ?. For more information, please follow other related articles on the PHP Chinese website!