Dereferencing NULL Pointer for Reference: Interpretation and Standard
In C , the following code raises the question of what the standard dictates:
int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref;
Specifically, is it permitted to dereference a NULL pointer to obtain a reference, and what is the outcome of such an operation?
Standard Interpretation
According to the C standard, dereferencing a NULL pointer is considered undefined behavior. This is explicitly stated in section 8.3.2/4 of the standard:
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.
Implementation Implications
In practice, however, many compilers implement this behavior as setting the result to NULL. This means that ptr2 in the code snippet provided would be assigned a value of NULL.
Compiler Interpretation
It's important to note that the behavior described above is not guaranteed by the standard and may vary across different compilers and platforms. For example, some compilers may raise an exception or perform other platform-specific actions when dereferencing a NULL pointer.
Specific Exception
One exception to this rule is the use of the sizeof operator on a NULL pointer. In this context, the dereference does not actually occur, and sizeof can be used to determine the size of the type without causing undefined behavior.
The above is the detailed content of Is Dereferencing a NULL Pointer to Obtain a Reference Defined Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!