Why is the Output 5 5?
It is because of something called "Undefined Behavior". Undefined Behavior do not have to always provide the wrong result.
After the function call is over then the local variable a
is removed. So p
should be pointing to invalid object.
Exactly, it is pointing to an invalid object or better said to no object at all - the int
object of a
allocated inside of the function f()
is already deallocated at the point of executing printf("%d",*p);
in main()
.
To dereference a pointer with an stored address to an no longer existant object is Undefined Behavior.
It could print out anything. That it print out 5
is just a lucky shot, but never reliable. Even when executing the exact same file a second time, you already could get a different result.