Accessing class members through a null pointer typically results in a crash. However, in C , certain non-virtual methods seem to work even with null pointers. This behavior raises several questions: how does this occur, and where is the object allocated?
In C , when a non-virtual method is called on a null pointer, the compiler generates a direct call to the function associated with that method. It does this by passing a hidden parameter (pointer to the object) to the function.
In the example provided:
class Foo { void say_hi(); }; Foo* foo = nullptr; foo->say_hi();
The compiler transforms this into:
void Foo_say_hi(Foo* this); Foo_say_hi(foo);
Since the say_hi method never references the object's members, it doesn't dereference the null pointer and thus avoids the error.
Formally, calling any method on a null pointer is undefined behavior. However, compilers may optimize code by assuming that the object is not null. This is risky because it can lead to unexpected behavior.
In the case of the example, the compiler optimizes the non-virtual method call to avoid a crash. However, it's important to note that this behavior is not guaranteed. Calling non-virtual methods on null pointers should still be avoided as it may lead to unspecified results.
The object referred to by the foo pointer in the example is not allocated within the main function. A local variable with type Foo* is created on the stack, and the value assigned to it is a null pointer. This means that the object itself does not exist anywhere in memory.
The above is the detailed content of Why Do Non-Virtual Method Calls on Null Pointers Sometimes Avoid Crashes in C ?. For more information, please follow other related articles on the PHP Chinese website!