Home >Backend Development >C++ >Why is Dereferencing a NULL Pointer to Create a Reference in C Undefined Behavior?
C Standard: Undefined Behavior of Dereferencing NULL Pointer for Reference Creation
The C standard explicitly states that dereferencing a NULL pointer results in undefined behavior. This principle applies to the creation of references as well, as exemplified by the code provided:
int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref;
In this code, the compiler attempts to create a reference ref by dereferencing the NULL pointer ptr. According to the standard, this is undefined behavior, and the program's subsequent actions are unpredictable.
The note in 8.3.2/4 of the standard reinforces this point, stating that a null reference cannot exist in a well-defined program because it would require dereferencing a NULL pointer, which is undefined behavior.
It's important to note that defined behavior ensures predictable and consistent program execution, while undefined behavior leaves the program's outcome unspecified. Therefore, it's crucial to avoid relying on undefined behavior in your C code.
The above is the detailed content of Why is Dereferencing a NULL Pointer to Create a Reference in C Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!