I am testing the Iron-Cast rule which says:
"Never, ever, return the address of a local automatic variable from a function."
However, in the output from the program, the first cout prints correct value of 15 while the other prints a strange exponential number. I expected both to produce gibberish result. Why does the first cout produce correct result?
If there is any others statement like cout << " "; before the first cout << *p << std::endl; then I get gibberish both times.
Memory is allocated from stack for arguments and local variables, when you do call a function. After return, the memory is no longer allocated. Next time something needs stack memory, it will get that available block.
What you call "correct result" -- the 15 -- is as much gibberish as the printed other values. It just a fluke that with your compiler and specific code the bytes, where the tripple() did store value "15", were not reused by anything else before the dereference operation.
My guess is that the memory where the variable was stored has not yet been used for anything else so it still contains the old value you gave it. When the << operator is called it probably uses its own local variables that overwrites the memory where y in tripple was previously stored.
It doesn't print a correct result. There is no such thing as a "correct" result when you evoke undefined behavior, or perhaps it would be better to say that every possible result is equally correct.
I was expecting it to be some coincidence as well, anyway. I take note that what the program did is by definition "undefined behaviour" and thus one must not indulge in it.