c++c++11crash

The program may not crash when the program derefrences a null pointer?


I used to believe that the program would crash at once when dereferencing a null pointer.

But the code snippet below works well. What a surprise!

#include <iostream>
#include <vector>

struct foo
{
    void test()
    {
        std::cout << "This is displayed\n";
    }
};

int main()
{
    foo *f = nullptr;
    f->test();
}

Solution

  • Your code does not actually look at the this pointer that is passed as a hidden first argument to the member function. Which is how it survived. If you add something that would make use of this, like making the function virtual, it will crash as you expected.

    https://godbolt.org/z/YfxcdqdPj

    Of course undefined behavior is undefined, the compiler is permitted to do absolutely anything in this case, so logical reasoning will only get you so far.

    If you enable optimizations, the compiler can also just plonk a ud2 instruction in there (explicit crash).

    https://godbolt.org/z/YWfMefYoG