Home > Backend Development > C++ > Why Do Non-Virtual Method Calls on Null Pointers Sometimes Avoid Crashes in C ?

Why Do Non-Virtual Method Calls on Null Pointers Sometimes Avoid Crashes in C ?

DDD
Release: 2024-12-14 09:29:12
Original
836 people have browsed it

Why Do Non-Virtual Method Calls on Null Pointers Sometimes Avoid Crashes in C  ?

Non-Virtual Method Calls and Null Pointers: A Paradox

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?

Understanding Non-Virtual Method Calls

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();
Copy after login

The compiler transforms this into:

void Foo_say_hi(Foo* this);

Foo_say_hi(foo);
Copy after login

Since the say_hi method never references the object's members, it doesn't dereference the null pointer and thus avoids the error.

Undefined Behavior and Compiler Optimization

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.

Object Allocation

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template