#include "stdafx.h"
#include "iostream"
#include "conio.h"
usingnamespace std;
int* sendF()
{
int i = 123; // i is a local variable (declared on the stack), initialised with 123
int* tr=&i; // tr is a local pointer (declared on the stack), intitalised with the address of i
return tr; // return the address of local variable i
} // tr and i go out of scope and the memory is free to be reused by the next function call (that uses the stack)
int _tmain(int argc, _TCHAR* argv[])
{
int* t; // uninitialised pointer to an int
t=sendF(); // assign the address of sendF local variable i to t
cout<<*t; // dereference t, that is, get the value that happens to be at that address (which can be overwritten outside of our control)
getch();
return 0;
}
Means we get the value of i, because till that time that address not over written.
In case on address of 'i' some other value over written by any other function then we don't get value of i on calling 'sendF()'.
Means Idly we should not return address of local variable.