1

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;
}
Jashaszun
  • 9,207
  • 3
  • 29
  • 57
karan kapoor
  • 91
  • 1
  • 7

2 Answers2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I did it intentionally..What i want to know is why the output is different on machine and ideone ? Any possible reason for that ? – karan kapoor Jul 28 '15 at 16:00
  • @karankapoor The answer has already been stated: UB (undefined behavior). What this means is that *anything* can happen, including your computer suddenly exploding or becoming a black hole. Literally anything. (Just kidding, but really, it is unspecified and implementation-dependent.) – Jashaszun Jul 28 '15 at 16:02
  • @karan kapoor When a program has undefined behaviour you can not say what will be the result. For example calling operator << for std::cout can overwrite the memory early used by the function. – Vlad from Moscow Jul 28 '15 at 16:03
  • Also output of 10 suggests that value is preserved..How come that ? – karan kapoor Jul 28 '15 at 16:03
  • @karan kapoor Your program should not output 10 because you wrote *(fun()) = 30;. The fact that it outputs 10 is the result of the undefined behaviour. In any case it in most depends on whether the memory was already overwritten ot was not.:) – Vlad from Moscow Jul 28 '15 at 16:06
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.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57