understanding pointers

I have this code segment here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include<iostream>
using namespace std;
int * foo(){
	int a = 5;
	return &a;
}

void boo(){
	int a = 7;
}

int main(){
	int * p = foo();
	boo();
	cout << *p << endl;
}


what I don't understand is why the output is 7, and not segmentation fault. From what I know, both of a's are stack variables, so they should die as soon as I exit foo and boo functions, and p should be a dagnling pointer. what am I missing here? Thanks for the help.
Last edited on
Look up 'undefined behavior'.

The compiler could refuse to compile the program, if it wanted to.

By the way:
http://www.lb-stuff.com/pointers
Last edited on
I tried comiling on linux and windows, in both cases it worked.
No, in both cases the program continued running in a corrupted state, allowing for bad things to potentially happen (imagine: losing your 10-page essay because a programmer "tried comiling on linux and windows, in both cases it worked"). I would not say that "worked".

Read more in-depth on undefined behavior and why it is the way it is.
Last edited on
I tried comiling on linux and windows, in both cases it worked.

As LB pointed out, the behavior is undefined. That means the program might crash, or it might not compile, or it might display 7, or it might display a random value.

You might run it a million times and it might display 7, then on the million and one'th time, it displays some other number. In fact, on many systems this is exactly what will happen.

Why does it display 7? Because a in foo and a in var happen to be allocated at the same address on the stack and the system happened to put nothing there between the calls.

Why didn't you get segmentation violation? There's a difference between the what memory the C++ program is using at any given time and what memory the operating system has allocated to it. A SEGV will happen if the program tries to allocate memory that the OS has not allocated to it. In this case, the OS allocated some memory, the stack can grow into that memory, but the program isn't currently using it.

Why might the result be different after a million runs? It's the fact that p probably points to the far side of stack pointer. If the computer gets an interrupt between the call to boo() and the time that you print *p, then it might, depending on the computer, use the program's stack when servicing the interrupt. That means it might write who-knows-what at that location.

This may all be interesting, but you can't rely on any of it. To reiterate, the behavior is undefined. The program can do whatever it wants. There is no such thing as "incorrect" behavior in this case.
Topic archived. No new replies allowed.