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
  • 90,666
  • 33
  • 258
  • 416

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
  • 74,840
  • 36
  • 166
  • 272
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,112
  • 1
  • 17
  • 24