0

when passing a=4, the given functions returns :

int* temp1(int a)
{
   int b = a*2;
   return &b;
}

int* temp2(int a)
{
   int b = a*2;
   int *p = &b;
   return p;
}

int main()
{
   cout << *temp1(4);  // error
   cout << *temp2(4);  // output = 8
}

Why these above two functions have different behaviour? Whereas, the below have same outputs?

int a = 3;
cout << *(&a); // 3

and

int a= 3;
int *p = &a;
cout << *p; // 3
  • 4
    Both functions are undefined behavior: [https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – drescherjm Apr 16 '20 at 15:51
  • There is no difference, but beware you are returning the address of a local variable (allocated on the function's stack frame) which is automatically deallocated when the function call is finished so the caller is pointing to invalid memory. – wcochran Apr 16 '20 at 15:53

1 Answers1

4

The behavior of both of your functions is identical. Both return a pointer to a local variable. The pointed-to objects' lifetimes both end when the function returns. Therefore the behavior of your program is undefined if it dereferences either of the returned pointers.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • The last part is a very good point. It's only UB if you actually attempt to use the returned pointer. Although then you question what is the point of a function returning a pointer if using that pointer is not allowed. – drescherjm Apr 16 '20 at 15:59