Search code examples
c++

Will this lead to null pointer dereference?


In the following code, a SomeClass object is scoped inside a block but a reference to it is stored in p in an outer block. And later using p, SomeMethod() of SomeClass is called.

SomeClass TestMethod(SomeClass c) {
    SomeClass * p;
    {
        SomeClass t;
        p = &t;
    }
    p->SomeMethod();
    return *p;
}

Will p->SomeMethod() fault due to a null pointer dereference?

I tried using int in place of SomeClass and didn't get a null pointer dereference. But I want to understand the behaviour according to the C++ standard.


Solution

  • No, this will not necessarily lead to a null pointer dereference. p was assigned some non-null value within the block. Just because the thing it points at has ended its lifetime doesn't mean the value (pointer value) stored in p will become nullptr magically.

    However, this is still undefined behavior if SomeMethod is a non-static method, because (assuming SomeClass is a class type - heavily implied) the lifetime of t ends at the end of the block.