1
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?

Vittorio Romeo
  • 86,944
  • 30
  • 238
  • 393

2 Answers2

6

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.

Shoe
  • 72,892
  • 33
  • 161
  • 264
5

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

rems4e
  • 3,047
  • 1
  • 16
  • 24