0

This code snippet:

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

int main()
{
  int* p = fun()
  cout<<*p;
}

as the above variable t goes out of scope as the function call ends and pointer storing address of variable that does not exist gives no error and works properly....confused why why??

cigien
  • 57,834
  • 11
  • 73
  • 112
Asker
  • 1
  • 1
  • 2
    As the target says, what you have is UB. That means anything can happen, including appearing to give the right result. This is, of course, not guaranteed. – cigien Jul 05 '21 at 14:10
  • fwiw `return &t;` would let gcc issue a warning https://godbolt.org/z/hf4qxoKob. You already obfuscated the matter enough such that gcc nor clang dont bother to diagnose. Concerning "works properly": try to turn on compiler optimizations – 463035818_is_not_an_ai Jul 05 '21 at 14:15
  • 1
    Just because a C++ program runs and appears to give the right result does not guarantee that it's bug free. This is actually a very important lesson to learn. – Sam Varshavchik Jul 05 '21 at 14:15

0 Answers0