Does a pointer extend the lifetime of an automatic-storage variable?

809 Views Asked by At
int main() 
{
    float* ptr;

    {
        float f{10.f};
        ptr = &f;
    }

    *ptr = 13.f;
    // Do more stuff with `*ptr`...
}

It it valid or undefined behavior to use/access *ptr?

I tested situations similar to the above example and everything seems to work as if the lifetime of the variable in the nested block was extended thanks to the pointer.

I know that const& (const references) will extend the lifetime of a temporary. Is this the same for pointers?

2

There are 2 best solutions below

0
On BEST ANSWER

It's undefined behavior because you are accessing an object that has been deallocated.

The variable f is declared within that specific block of scope. When the execution flow reaches:

*ptr = 13.f;

the object has been deallocated and ptr points to the old address of f.

Therefore no, the lifetime of f has not been extended.

0
On

The float will go out of scope and your pointer will reference a non-allocated memory region -> using it will lead to UB.