Pointer value after Scope not NULL

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

int* sendF()
{
	int i = 123;
	int* tr=&i;

	return tr;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int* t;

	t=sendF();
	
	cout<<*t;
	getch();
	return 0;
}

O/P :- 123

Why the local pointer(tr) value get out side its scope?
Idly it should be NULL/garbage.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace 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;
}
Last edited on
it is garbage, it just hasn't been overwritten yet because you examined it in the next instruction.
Thnax guys kbw and Jaybob66.

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.
Topic archived. No new replies allowed.