Home > Backend Development > C++ > body text

Why Does Invoking a Method Through a Null Pointer in C Sometimes Work?

Mary-Kate Olsen
Release: 2024-11-01 02:27:27
Original
923 people have browsed it

Why Does Invoking a Method Through a Null Pointer in C   Sometimes Work?

Understanding Undefined Behavior: Null Pointer Method Invocation in C

Despite the seemingly intuitive expectation of an error, invoking methods through null pointers in C may appear to execute. This behavior raises questions regarding the standard compliance and optimization practices used by compilers.

To delve into this matter, consider the following example:

<code class="cpp">#include <iostream>
using namespace std;

class test
{
    int i;
public:
    test():i(0){ cout << "ctor called" << endl;}
    void show()
    {
        cout << "show fun called" << endl;
    }
};

int main(int argc , char *argv[])
{
    test *ptr = NULL;
    ptr->show();
    return 0;
}</code>
Copy after login

In this snippet, a class test is defined with a constructor and show() method. In the main() function, a pointer ptr is initialized to NULL and then the show() method is invoked through ptr.

Surprisingly, the program executes without errors and prints "show fun called" without triggering the constructor. This is due to the fact that in C , the compiler knows the type of the null pointer, enabling it to identify the method's code. Since the show() method does not utilize the this pointer, it runs successfully.

However, this behavior is considered undefined in the C standard. Compilers are permitted to optimize code by not checking if a pointer is NULL before calling a method. While this optimization improves efficiency, it compromises safety and predictability.

The above is the detailed content of Why Does Invoking a Method Through a Null Pointer in C Sometimes Work?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!