Getting erronous output

时间:2015-07-28 15:54:10

标签: c++ pointers c++11

following code gives output 10 on machine and 0 on ideone. What can be the reason ?

#include<iostream>
using namespace std;

int *fun()
{
    int x = 10;
    return &x;
}

int main()
{
    *(fun()) = 30;
    cout << *(fun());
    return 0;
}

2 个答案:

答案 0 :(得分:3)

You return a pointer to a local variable of function fun that will be destroyed after exiting the function because it has automatic storage duration.

So the program has undefined behaviour.

If you want the program would work correctly at least define the function the following way

int *fun()
{
    static int x = 10;
    return &x;
}

In this case the local variable of the function will have the static storage duration and will preserve its value between function calls.

答案 1 :(得分:2)

Undefined behavior is what's happening. You can't use references to x outside of function fun, because it's defined on the stack and is out of scope.

If you want this to work correctly, @VladfromMoscow has the solution: make x a static int so that it is kept even when fun ends.