0

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

Returning the address of a variable inside a function is bad because that variable will no longer exist if the stack frame where the variable belongs end.

So why this code works fine

int* test(){
    int a = 11;
    return &a;
}

int main(){

    int *a;
    a = test();

    cout << *a;

    return 0;

}
Community
  • 1
  • 1
user1393669
  • 43
  • 1
  • 2

2 Answers2

5

So why this code works fine

Undefined behaviour means the code can appear to work fine. But it's still undefined.

In your case, a is a dangling pointer.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • so I should avoid doing this? – user1393669 Aug 08 '12 at 18:07
  • 1
    @user1393669 not only avoid. You should explicitly not do this. – Luchian Grigore Aug 08 '12 at 18:08
  • @user1393669 Undefined behavior is compiler/machine specific. It may work fine on your machine, but it may crash on someone else's. – gcochard Aug 08 '12 at 18:08
  • Yes. Avoiding *undefined behavior* is always a good thing. Programs like defined behavior a lot better and produces as many bugs / defects. – Thomas Matthews Aug 08 '12 at 18:08
  • dangling pointer points to random memory address right? so why when I compile the output is still 11 – user1393669 Aug 08 '12 at 18:10
  • 1
    @user1393669: Basically, you're using the variable before the computer happens to get around to cleaning it up. There is absolutely no guarantee that it won't clean it up before you use it, you're just currently getting "lucky" in your exact test case. – KRyan Aug 08 '12 at 18:10
0

The code is still wrong. It may appear to work now, but won't next week. It may appear to work now, but change one small thing and it no longer "works".

Try this. Add another function, test2:

int *test()
{
    int a = 11;
    return &a;
}

int test2()
{
    int b = 13;
}

int main()
{
    int *a;

    a = test();
    cout << "after test: " << *a << endl;

    test2();
    cout << "after test2: " << *a << endl;

    return 0;
}

Now is 11 printed both times? Note that it could still print 11 twice, but it probably won't. We are, after all, still flirting with undefined behavior here.

But on my machine, I see:

after test: 11
after test2: 13

test2 has clobbered the space on the stack that my dangling pointer was pointing to. The code is incorrect. The variable defined inside the function test is out of scope when the function exits, and is no longer valid. Maintaining a reference to it doesn't change this.

pb2q
  • 58,613
  • 19
  • 146
  • 147