3

Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable's memory be accessed outside its scope?

#include<iostream>
using namespace std;

int *p = NULL;

void 
fun(void){
    int i = 10;
    p = &i;
}

int 
main(void){
    fun();
    cout<<*p<<endl; //#1
    cout<<*p<<endl; //#2
    return 0;
}

I think #1 and #2 will output the same, but why #1 output 10 and #2 output a random number?

Community
  • 1
  • 1
bitstore
  • 326
  • 2
  • 10
  • 5
    You're making a pointer point to a stack variable which is destroyed and then dereferencing the pointer, producing undefined behaviour – Seth Carnegie Jan 03 '12 at 15:52
  • 1
    Undefined behavior which means you can get the expected output (http://ideone.com/VMYzG) or some other result (http://codepad.org/OiN8n1L0) – UncleBens Jan 03 '12 at 16:20

5 Answers5

8

This is just undefined behavior. You're working with a pointer to a local variable, after that variable has gone out of scope. Anything could happen.

unwind
  • 391,730
  • 64
  • 469
  • 606
3

This is indeed a dangling pointer.

You are assigning p to point to an automatic (local) object. Once fun has returned, the object no longer exists, and attempting to access it through p gives undefined behaviour.

If you're interested in why you observe that particular behaviour: on most platforms, the stack frame of fun will still exist until another function is called. So reading p for the first call to << is quite likely to find the old value of i. After calling <<, the old stack frame has most likely been overwritten, so reading p will find an arbitrary value. But none of this is behaviour you can rely on; accessing the dead object could cause a crash, or any other behaviour.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • +1 for explaining possible causes for output. While UB can't be relied on, one needs to be able to recognize the effects. – UncleBens Jan 03 '12 at 16:24
1

Yes, p becomes a dangling pointer the moment fun() returns.

jrok
  • 54,456
  • 9
  • 109
  • 141
1

You are saving a pointer to a variable that is out of scope. Thus, the behavior is undefined. It can print anything, or even crash your application. Or even make your computer explode.

1

Your function is returning a pointer to something that gets over-written:

int i = 10;
p = &i; // This line

Because i is a local variable.

Peter K.
  • 8,028
  • 4
  • 48
  • 73