When does invoking a member function on a null instance result in undefined behavior?

Posted by GMan on Stack Overflow See other posts from Stack Overflow or by GMan
Published on 2010-03-18T23:20:44Z Indexed on 2010/03/18 23:31 UTC
Read the original article Hit count: 414

This question arose in the comments of a now-deleted answer to this other question. Our question was asked in the comments by STingRaySC as:

Where exactly do we invoke UB? Is it calling a member function through an invalid pointer? Or is it calling a member function that accesses member data through an invalid pointer?

With the answer deleted I figured we might as well make it it's own question.


Consider the following code:

#include <iostream>

struct foo
{
    void bar(void) { std::cout << "gman was here" << std::endl; }
    void baz(void) { x = 5; }

    int x;
};

int main(void)
{
    foo* f = 0;

    f->bar(); // (a)
    f->baz(); // (b)
}

We expect (b) to crash, because there is no corresponding member x for the null pointer. In practice, (a) doesn't crash because the this pointer is never used.

Because (b) dereferences the this pointer (this->x = 5;), and this is null, the program enters undefined behavior.

Does (a) result in undefined behavior? What about if both functions are static?

© Stack Overflow or respective owner

Related posts about c++

Related posts about undefined-behavior