Why does a pointer, on dereferencing still returns the value of a variable which is no more?

Hi all,
I was playing with some C++ code and came upon a doubt.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <conio.h>

using namespace std;

int * givepointer();

int main(){
    int *ptr;
    ptr = givepointer();
    cout << *ptr << endl;
}

int * givepointer(){
    int x = 2;
    int *k = &x;
    return k;
}



This program gives the output 2.
I want to ask that after givepointer returns the address of variable x, it deletes the variable x( since all the variable in a function gets deleted once the function has completed executing ). Now, ptr has a address which points to nothing. But, in spite of this, when we dereference it, it successfully displays the output 2.

Why is this happening?

Waiting for your reply,
Thank you.

Q : ( since all the variable in a function gets deleted once the function has completed executing )

A: Variables don't delete when they get executed.

Q : ptr has a address which points to nothing.

A : Yes it does, basically you are saying that the pointer ptr in main is equal to the pointer k in givepointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <conio.h>

using namespace std;

int * givepointer();

int main(){
    int *ptr;
    ptr = givepointer(); //this pointer is equal to the k pointer in givepointer so that means it will = 2.
    cout << *ptr << endl;
}

int * givepointer(){
    int x = 2; //x = 2
    int *k = &x; //k = 2 because it is referencing x.
    return k;  //you return 2 because k = 2.

}


here is something that might help you :

http://www.cplusplus.com/reference/new/operator%20delete/

https://www.youtube.com/results?search_query=delete+operator+c%2B%2B&oq=delete+operator+c%2B%2B&gs_l=youtube.3...9109.10281.0.10661.9.9.0.0.0.3.146.800.7j2.9.0...0.0...1ac.1.11.youtube.Hx1Pcr3oIP4
A small correction to what Hertz just said.
You are not returning 2. You are returning some memory address such as 0x70123abf (I just made that number up).
The variables do not get deleted, but they are freed. Meaning if nothing new overwrites it then it will still be there. Peter beat me with a better explanation, before I finished that edit.
Last edited on
The function returns a pointer pointing to the memory address that x was stored at. That memory will not just magically go away. If it hasn't been reused to store other things it will still contain the same value as x did, so that is why you still get 2 by reading from that memory location.

You shouldn't rely on this behaviour. It is just a coincidence that it happened to "work".
@ Cubbi: hahaha. Thank you friend, you cleared all my doubts regarding this topic. I must say that whoever has written this analogy is the best teacher for teaching C++.

Also, thank you all the other people who have answered this question. You did a really good job explaining.

-Himansh
Originally Posted by Cubbi:
This calls for the hotel key analogy: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794


I like it, I like it!
Right this may not be entirely correct in terms of computer science but I want to try and put it simply.

When you create a variable you're assigning it a piece of memory on the computers RAM. When a variable is removed from a program, chances are that the actual data will just remain there until more memory is needed by another program and that data is changed.

I suppose you could imagine the storage in RAM as many little boxes inside a warehouse, and a pointer is an catalog of where you will find each box (on which isle of the warehouse they're in)

When you need to store a new variable you look for an unused box, empty out its current contents and store your new stuff there. The box still stays in the same location in the warehouse and therefore your catalog (or pointer) is still valid. However in programming it's NOT okay to try and de-reference an unknown pointer because you don't know what's actually inside that box, and trying to read it as something else to what it actually is could be critical to your program.

I hope that helps but I do have a bad feeling I may have just created an awful lot of confusion :/
@SatsumBenji: You explained this concept in a very good way. It removed the little confusion which I had earlier. Good Work :)
WOOHOOO... Go me XD.

If you keep in mind that variables are stored in boxes somewhere on your RAM and a pointer is telling the computer where that box is, I'm sure you'll find that you may be able to work around a few problems you possibly run into.
The most important things with programming is problem solving, as long as you can get a way of thinking about things that you can understand, things become much easier.
@SatsumaBenji:
Yeah, I completely agree on what you said. If anyone wants a visual representation of what SatsumaaBenji said, go ahead and watch this awesome video,

https://www.youtube.com/watch?feature=player_detailpage&v=VuqXDYovNyY

Topic archived. No new replies allowed.