c++variablespointersstorageautomatic-storage

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


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?


Solution

  • 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.