That's certainly undefined behavior (by common sense, and by the wording of the standard).
As far as the standard goes, 3.8/5 is rather concrete about what is allowed and about what isn't:
[...] after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways [...] and using the pointer as if the pointer were of type void*,
is well-defined.
Indirection [...] is permitted [...] as described below. The program has undefined behavior if:
- ...
- [...] used as operand of static_cast
, except when the conversion is to pointer to cv void
, or to pointer to cv void
and subsequently to pointer to either cv char
or cv unsigned char
- [...] used as the operand of dynamic_cast
The object's storage ends at the end of the scope per 3.7.3/1 (in practice this is most likely not true, the stack frame will probably be reset at the end of the function, but formally that's what happens). Therefore, the dereference doesn't happen after the end of lifetime but before the release of the storage. It happens after release of the storage.
The special conditions under which you may dereference the pointer anyway do therefore not apply (the same is true for any similar paragraphs with the same precondition such as 3.8/6).
Further, assuming that the previous paragraph wasn't true, it is only allowable to dereference the pointer as cv void*
or to cast it to cv char
(signed or unsigned) prior to dereferencing. In other words, you are not allowed to look at the pointed-to int
as if it were an int
. As stated in 3.8/5, the int*
is really only a mere void*
after the lifetime of the object. Which means dereferencing it as int*
is the equivalent of doing a cast (not explicitly, but still).
One would really wish that this attempt produces an error, but I guess that's a really tough one for the compiler to detect. The pointer itself is well and alive, and it has been safely derived by taking a valid object's address, that's probably near impossible to diagnose.