Home  >  Article  >  Backend Development  >  Can You Access Static Members in C Using Null Pointers Without Undefined Behavior?

Can You Access Static Members in C Using Null Pointers Without Undefined Behavior?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 11:53:03183browse

Can You Access Static Members in C   Using Null Pointers Without Undefined Behavior?

Accessing Static Members Using Null Pointers in C

In C , static members of a class can be accessed through a null pointer without invoking undefined behavior. This behavior, which may seem surprising, can be explained by examining the language's definitions and rationale.

Evaluation of Uninitialized Pointers

When accessing a class member through a null pointer, the behavior is well-defined as long as the evaluation of the operand does not require the referent's identity or stored value. For example, accessing a static member variable d->a merely evaluates the expression *(d) to obtain the reference to the object, but does not perform operations that require the referent to be initialized.

This evaluation process is supported by [expr.ref]/2, which states that d->a is converted to ((d)).a. The evaluation of ((d)), represented by *d, proceeds without triggering any errors because the object referenced by d is not required.

Indirection Through Null Pointers and Undefined Behavior

The C standard does not explicitly state that indirection through a null pointer inherently results in undefined behavior. In fact, CWG issues #232 and #315 suggest that mere indirection is not problematic.

The primary argument for this stance lies in the existence of well-defined scenarios where indirection through null pointers is permitted. For instance, [expr.typeid]/2 allows typeid(*((A*)0)) to throw a bad_typeid exception, even though *d evaluates to null. If mere indirection invoked UB, this statement would not be well-defined.

Implications for Your Program

In your example,

<code class="cpp">int main()
{
    demo* d = nullptr;
    d->fun();
    std::cout << d->a;
    return 0;
}</code>

the program compiles and runs without errors because invoking static member functions or accessing static variables does not require the identity of the referent. Your program, therefore, does not have any inherent issues or undefined behavior.

The above is the detailed content of Can You Access Static Members in C Using Null Pointers Without Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn