Home >Backend Development >C++ >Why Does Calling a Non-Virtual Member Function on a Null Pointer in C Sometimes Work?
Gotcha in C : Accessing Non-Virtual Class Members on a Null Pointer
In C , calling non-virtual member functions on a null pointer may unexpectedly work, posing a curious puzzle. Let's delve into this behavior through an intriguing code snippet:
Puzzle Explained
The confusion arises from the different mechanisms used to call virtual and non-virtual methods.
In the given code, the non-virtual method say_hi() never explicitly dereferences the this pointer, bypassing the null pointer dereference error. It's essentially the equivalent of a function call with a parameter passed by value:
Undefined Behavior
Technically, calling any function (even non-virtual) on a null pointer is undefined behavior in C . However, some compiler implementations may provide well-defined behavior for specific scenarios, such as the above non-virtual function call.
Caution
While the unexpected behavior may seem convenient, relying on it is risky and not a best practice. Always avoid accessing class members on null pointers, as it can lead to unexpected and unpredictable results.
The above is the detailed content of Why Does Calling a Non-Virtual Member Function on a Null Pointer in C Sometimes Work?. For more information, please follow other related articles on the PHP Chinese website!