EarlyIreland EarlyIreland - 4 months ago 16
C++ Question

Pointer declared outside of try/catch but initialized inside causes undefined behaviour?

I have a some code that looks like the following:

class ClassA
ClassA(string p1, string p2);
void DoSomething();

int main()
ClassA *p = NULL;

// ...
// some external input that can throw
// ...
ClassA a{"some", "params"};
p = &a;
// print error

if (p != NULL) {
p->DoSomething(); // <- causes segfault

Apologies if this is bad/stupid code (I'm new to C++), but why does calling
cause segfaults to occur? Clearly,
is declared out of the try/catch block's scope, and the
p != NULL
always returns true, showing that
is not null and thus was properly initialized inside of the try/catch block.

Can someone help me understand this?


The pointer is initialized to point to an instance of an object in automatic inner scope.

When execution thread leaves the scope, the object is destroyed, and the pointer is now pointing to a destroyed object.

And a thrown exception, of course, leaves the scope where the object is declared.

In other words, the object that the pointer is pointing to only exists inside the try block, and as soon as execution leaves the try block, naturally, or via a thrown exception, the object gets destroyed.

The fact that the exception gets the caught by the catch block, is irrelevant.

This is yet another reason to use smart pointers. If the object gets allocated in dynamic scope, and the pointer in question is a unique_ptr or a shared_ptr, the object remains perfectly accessible, via the smart pointer, in the catch block, with no additional work required.