Warning : returns address of a local variable YET correct output

This is a discussion on Warning : returns address of a local variable YET correct output within the C Programming forums, part of the General Programming Boards category; This problem was suggested to me by a friend.
The code is -
Code:
/* Returning a pointer to an ...

Compiling this on GCC gives the above warning because k is a local variable and it will go out of scope once the function returns. Yet, when I run the program I get a perfectly correct output. That is 35. Why is this? Shouldn't I be getting garbage value?

Because the way memory was handled in this case, happened to work in your favor. But once the variable goes out of scope, you have no guarantee that the space won't be allocated to something else, or changed entirely. It's not that it never works, it's that it's never reliable. It's undefined.

As with most storage systems (memory or disk drive), the less work and effort put towards a pointless activity, the faster it is.

The value that was in-scope during the function was on the stack. There is no reason the computer should take the time to "clean up", zero out, or otherwise randomize past values residing in memory. The value that was there (the 35) simply continues to reside there until there is a compelling reason to overwrite that same location.

I would not agree that it's a coincidence as tabstop does. I'd say there's a 100% chance that value will be there given the exact same conditions, compiler, order of code, etc.

I bet a 1000 byte chunk of memory is still intact after a free() as well... If I claimed it was "coincidence" that all 1000 bytes were exactly the same as before, that would be statistically astronomical and I should buy lottery tickets.

I would not agree that it's a coincidence as tabstop does. I'd say there's a 100% chance that value will be there given the exact same conditions, compiler, order of code, etc.

I don't.

1. Stack frame of this function is created on the stack such that the variable in question exists precisely on a page boundary.
2. Function returns.
3. Program gets scheduled out.
4. Memory pressure on the system causes swap algorithms to activate.
5. Stack space below the stack pointer is discardable, so it can be unmapped.
6. Program gets scheduled back in.
7. Program tries to access memory below the current stack pointer.
8. This page is unmapped.
9. EXPLOSION