Dereferencing NULL Pointers for References
The C standard explicitly addresses the behavior of dereferencing a NULL pointer to obtain a reference. This practice is considered undefined behavior.
In the example provided:
int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref;
The attempted dereferencing of the NULL pointer ptr is considered undefined behavior. According to the standard (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.
Therefore, assigning a reference to the dereferenced NULL pointer is invalid, and the behavior is not well-defined. The result of using ptr2, which points to the reference obtained from the dereferenced NULL pointer, is also undefined.
One exception to the prohibition on dereferencing NULL pointers is when used with the sizeof operator. In this context, the pointer is not actually evaluated, so dereferencing it does not cause undefined behavior. However, this exception is limited to the sizeof operator.
The above is the detailed content of What Happens When You Dereference a NULL Pointer to a Reference in C ?. For more information, please follow other related articles on the PHP Chinese website!