Accessing Class Members on a NULL Pointer: Anomalies and Explanations
In the provided C code snippet, it was observed that a function call to a non-virtual method succeeded even when the object pointer was NULL, while a virtual function call caused the application to crash. This curious behavior raises two fundamental questions:
1. How does a non-virtual method work on a NULL pointer?
Unlike a virtual function call, a non-virtual function call does not require a vtable lookup. The compiler directly translates the function call into a machine code instruction that points to the specific function to be executed. The function is passed a pointer to the object that the function is called on as a hidden parameter.
In the given code, the function say_hi() does not make any reference to members of the Foo class. Therefore, it can be executed without the need to dereference the this pointer. Essentially, the call to say_hi() is equivalent to:
void Foo_say_hi(Foo* this); Foo_say_hi(foo); // where foo is NULL
Since the function never attempts to access the object's members, it does not encounter the undefined behavior of dereferencing a NULL pointer.
2. Where does the object foo get allocated?
In the provided code, foo is declared as a local variable of type Foo*. Since it is not given a specific memory allocation, it is most likely allocated on the stack for the main function, just like other local variables. However, the value stored in foo is a NULL pointer, indicating that it does not point to a valid object instance of type Foo.
The above is the detailed content of Why Does a Non-Virtual Function Call Succeed on a NULL Pointer While a Virtual Function Call Fails?. For more information, please follow other related articles on the PHP Chinese website!