Accessing Class Members on a NULL Pointer: Exploring Non-Virtual Method Behavior
Question:
Why does a non-virtual method call succeed on a NULL pointer in C , while a virtual method call crashes the program?
Answer:
Non-Virtual Method Behavior:
When a non-virtual method is called on a NULL pointer, the compiler generates code that directly invokes the method's implementation. This is achieved by passing a hidden "this" parameter to the function, which in the case of a NULL pointer, points nowhere. However, the method itself does not attempt to access any members of the object, so the code avoids dereferencing the NULL pointer and operates as intended.
Formal Definition:
However, it's important to note that invoking any method on a NULL pointer is formally considered undefined behavior in C . This means that the compiler can make arbitrary choices about what happens, including allowing the program to run apparently correctly.
Virtual Method Behavior:
Virtual method calls require a vtable lookup to determine which implementation to invoke. The vtable is associated with the actual object, so calling a virtual method on a NULL pointer, which has no associated vtable, results in a crash.
Object Allocation:
The variable "foo" in the provided code is a local variable allocated on the main function's stack. However, it is initialized with a NULL pointer, indicating that it does not point to any valid object of type Foo.
The above is the detailed content of Why Do Non-Virtual Method Calls on NULL Pointers Succeed While Virtual Method Calls Fail in C ?. For more information, please follow other related articles on the PHP Chinese website!