question for functions that return pointers

This is a discussion on question for functions that return pointers within the C Programming forums, part of the General Programming Boards category; Hello, I need to know why the following piece of code works... It is strange for me...
Code:
#include <stdio.h>
...

It works by sheer dumb luck*. You return an address that was on the stack, but when fct is done, that address is invalid. The data (2) is still there simply because nothing else has come along yet and corrupted that part of the stack.

* It doesn't actually work, not by any reasonable definition. What that sort of behavior (accessing invalid memory) results in is undefined behavior: Question 11.33

If you were reading the rules of basketball and it said that you can't hold on to the ball and run with it, would you pick up the ball and try runing with it right then? And would you expect some magical force to suddenly stop you?

If you try that in a real game, you will quickly into problems, just as if you try doing what you're doing in a real world program you will quickly run into problems.

"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens

I never said I am using this, but, by mistake I compiled this piece of code, and I was wondering why it works correctly.

Alex,

It doesn't work correctly. A better compiler would stop the program with an error message. But that's quite hard to achieve. Most compilers don't protect memory which you've used and lost, and so it appears to be still there, for a short time. However it's liable to be overwritten at any point, not necessarily in the next function call (the compiler might be calling internal functions without you being aware of it), so it's not safe to use.