-1
#include <iostream>
using namespace std;
int *wedgic(int foo)
{
    cout<<foo;
    return (&foo);
}

int main()
{
    int fo=7;
    int *blah;
    blah=wedgic(fo);
    (*blah)+=3;
    wedgic(fo);
}

can anyone tell me why the result is 7 7 7 but no 7 7 10??

please help, I guess I dont understand what does Blah=wedgic(fo); do...

thanks

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
Keith Zhen
  • 13
  • 1
  • This program makes only *two* attempts to output anyhting. It cannot possibly output *three* numbers. Neither `7 7 7` nor `7 7 10` is possible. Either your code is fake, or your claim about its output is false. – AnT stands with Russia Aug 21 '12 at 23:05
  • Read this: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/ – NullUserException Aug 21 '12 at 23:16

2 Answers2

2

Firstly, your function wedgic returns a pointer to its local variable foo. The pointer becomes invalid immediately after the function wedgic terminates. Any attempts to use the returned pointer value lead to undefined behavior. In other words, you program produces no meaningful results. The behavior is undefined. Whatever you see there (7 7 7 or whatever else) is just an accident with no meaningful explanation.

Secondly, your program make only two attempts to output anything. Yet you claim that it somehow outputted three numbers. This is highly unlikely, even for a program with undefined behavior. It is either that your claim about the output is false, or you posted fake code. When you ask question about the results produced by some code, please, post real code.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

The problem is that wedgic() returns a pointer to its own local variable rather than the address of fo you declared in main().

The variable foo in wedgic() is a non-static local variable which means its lifetime does not extend beyond a call to this function. Returning a pointer to such a variable is just plain wrong since as soon as the pointer is used outside the function the thing it points to no longer exists.

Thus

(*blah)+=3;

is ineffective and in fact dangerous.

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92