Pointer to deallocated variable changes address

Accessing the return value of fun has implementation-defined behavior, as it returns an invalid pointer value (see the quote below, why). In particular platforms, it may even generate a runtime fault. So, p's value is implementation-defined as well. Most likely, it will became invalid pointer value, so accessing it is implementation-defined.

basic.std/4:

When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values. Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.


It is probably a compiler feature. In this case it is very easy to see that the pointer returned by fun will be invalid and thus further usage of the pointer will result in undefined behaviour. If you try a different compiler it might be different. E.g. for me in Visual Studio 2012 it does return the actual address instead of 0.