0

I know the lifetime of the local variable in the function will finish after the function completed. But I found the example shown below, it can work.

int & foo()
{
  int b = 5;
  int &a = b;

  return a;
}


int main()
{
  int &c = foo();
  cout<<c;

  return 0;
}

Also, I tried to use pointer to point the local variable and return the pointer. It can work too.

int * foo(){
    int b = 5;
    int *a = &b;

    return a;
}


int main()
{
    int *c = foo();
    cout<<*c;

    return 0;
}

I am so confused. I've learnt that the lifetime of the local variable will end after the function completed because the local variable is stored in the stack memory. It means that the memory of the local variable will be released after the function completed. Then, the pointer or reference will point to nothing.

However, the two example above verified that my concept is wrong. What is the reason?

Michael Tsai
  • 751
  • 2
  • 11
  • 21
  • It just happens to work. – arrowd Nov 26 '19 at 06:16
  • The word _work_ does not make sense here. It _works_ for you, since you expect `5` to be printed out. I expect `-1` to be printed, so for me, the program does not _work_. That's the consequence of _undefined behavior_. – Daniel Langr Nov 26 '19 at 07:03

1 Answers1

4

Your observation is called undefined behavior: The language does not place any restrictions on the behavior of the program. One of the possible manifestations of undefined behavior is that things look like they "work".

But you do not want to have any undefined behavior in your program. Do not use the construct even though they appear to work.

j6t
  • 9,150
  • 1
  • 15
  • 35
  • But can you explain why it can work? thanks. – Michael Tsai Nov 26 '19 at 06:19
  • There is not much point in arguing over a program with undefined behavior. Even though it seems to "work" today, it may stop "working" tomorrow. To satisfy your curiosity, look at the generated assembly code. – j6t Nov 26 '19 at 06:22
  • @MichaelTsai it does not work. Its like rolling a die, expecting a 1 and getting a 1, then conclude the die will always roll a 1. By far not the best analogy, but still it describes the situation better than "it works" – 463035818_is_not_an_ai Nov 26 '19 at 09:59