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.
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.
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.
By the time p->SomeMethod()
is called, the object that p
points at has already ended its lifetime, and p
has been left dangling. p
is not set to nullptr
automatically, and dereferencing p
for any reason will thus access an invalid object.
t
after the close of the inner braces) is undefined behaviour. I would assume thatt
is copy-constructed (or RVO'd) with whatever is returned bybuild()
.p
is still in scope when used, and definitely has the address of some out-of scope stack memory in it, so it won't beNULL
. However, the instance ofSomeClass
has been destroyed, and we don't know whatSomeMethod()
does. As it's UB all bets are off. – marko Commented Jan 2 at 0:27Someclass* p2 = new SomeClass; p = p2;
then the code would "work" (returning a copy of the heap-allocated object), but leak memory whenTestMethod
returns. – Tony Delroy Commented Jan 2 at 0:41SomeClass t = new SomeClass();
is very odd. DoesSomeClass
support doing this odd usage? (Without the code forSomeClass
, it's hard to tell.) – Eljay Commented Jan 2 at 13:14